简体   繁体   English

提交会话时发生休眠错误

[英]Hibernate Error When Commit session

This is my Code in DAOImpl (Hibernate): 这是我在DAOImpl(Hibernate)中的代码:

@Transactional
    public void insert(Cage cage) {

        Session session = null;
        Transaction tx = null;

        try{
            session = getHibernateTemplate().getSessionFactory().openSession();
            tx = session.beginTransaction();
            session.saveOrUpdate(cage);
            session.flush();
            session.clear();
            tx.commit();

        }catch(RuntimeException e){
            try{
                tx.rollback();
            }catch(RuntimeException rbe){
                rbe.printStackTrace();
                System.out.println("Couldn’t roll back transaction");
            }
            throw e;
        }finally{
            if(session!=null){
                session.close();
            }
        }
    }

When for the second time operations data entry (Same PK) takes place with this problem : 当第二次发生此问题的操作数据输入(相同PK)时:

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update org.hibernate.exception.ConstraintViolationException:无法执行JDBC批处理更新

As per your question 根据您的问题

When for the second time operations data entry (Same PK) takes place with this problem : org.hibernate.exception.ConstraintViolationException:

You are trying to insert same primary key twice. 您试图两次插入相同的主键。 You cant have same primary key for two entries in database. 数据库中的两个条目不能具有相同的主键。

Primary keys must contain UNIQUE values. 主键必须包含UNIQUE值。 Check this link http://www.w3schools.com/sql/sql_primarykey.asp 检查此链接http://www.w3schools.com/sql/sql_primarykey.asp

Keep primary key unique and you wont get this exception. 保持主键唯一,您将不会遇到此异常。 And if you need duplicate entries for that coloumn then dont make it a primary key 而且,如果您需要该列的重复条目,请不要将其设为主键

To auto generate id 自动生成ID

@Id @GeneratedValue(strategy= GenerationType.AUTO) @Column(name="\\"ID\\"") private int id; @Id @GeneratedValue(strategy = GenerationType.AUTO)@Column(name =“ \\” ID \\“”)私有int ID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM