java - 提交 session 时 hibernate 错误

标签 java 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();
            }
        }
    }

当第二次操作数据输入(相同的PK)时出现此问题:

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

最佳答案

根据你的问题

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

您正尝试插入相同的主键两次。 数据库中的两个条目不能具有相同的主键。

主键必须包含唯一值。 检查此链接 http://www.w3schools.com/sql/sql_primarykey.asp

保持主键唯一,您就不会遇到此异常。 如果您需要该列的重复条目,则不要将其设为主键

自动生成id

@Id @GenerateValue(策略= GenerationType.AUTO) @Column(名称=“\”ID\“”) 私有(private) int id;

关于java - 提交 session 时 hibernate 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37793781/

相关文章:

java - Spring Junit Hibernate @Transactional - 无 session

java - Hibernate:左连接中的 where 子句无法正常工作

Java EE 移动网站

java - Spring hibernate : dataSource via tomcat jndi

java - Spring - 使用 OpenSessionInViewFilter 为新线程提供 Hibernate session

java - 如何在没有此 ClassNotFoundException 的情况下连接到 Java 中的本地 SQLite?

java - Hibernate 和 Spring 事务——使用私有(private)构造函数/静态工厂方法

java - Bean 实例未加载

java - Java5 中的 Scanner 类抛出 java.lang.NullPointerException

Java/Swing JButton 不显示其文本且不执行其操作