简体   繁体   中英

Hibernate Error When Commit session

This is my Code in 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 :

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

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. Check this link 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 @GeneratedValue(strategy= GenerationType.AUTO) @Column(name="\\"ID\\"") private int id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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