Mohammad bana
Mohammad bana

Reputation: 23

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

Upvotes: 0

Views: 743

Answers (1)

kirti
kirti

Reputation: 4609

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;

Upvotes: 1

Related Questions