2

I have list of records of type class A ,let's say List<A> list=new ArrayList<A>();.

Now i am trying to a save every record of A into database by using session.save();. If my second records fails then rest of my records are failed. In that case i try to remove that second record from the session by using session.evict(obj). But still I am getting the same behaviour. Below is the code :

 for(A a:list){
    try{
    session.save(a);
    }
    catch{
    log.exception("Primary key");
    session.evict(a);
    }
    }
herry
  • 1,708
  • 3
  • 17
  • 30
  • 3
    You can't continue to use a session after an exception has occured. See also http://stackoverflow.com/questions/5109175/hibernate-session-is-invalidated-after-constraintviolationexception – isnot2bad Dec 13 '13 at 14:23
  • 2
    I think you'll have to rework your logic, because after an exception has been thrown in Hibernate, the behavior is unpredictable. – Boris Treukhov Dec 13 '13 at 14:24
  • After exception also i can still use the session object. – ravindranath Dec 13 '13 at 14:31

3 Answers3

0

call saveOrUpdate(a) instead of session.save(a);

edit

start transaction
    session.saveOrUpdate(a);
    a.getId() // this should have id.
    return a;   
end transaction
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

As per your code I have not seen session.flush(); session.clear(); this methods in your code. so update your code as follows

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
int i = 0;
for(A a:list){
    try{
        session.save(a);
        if (i % 20 == 0 ) { 
            //20, same as the JDBC batch size
            //flush a batch of inserts and release memory:
            session.flush();
            session.clear();
        }
        i++;        
    } catch {
        log.exception("Primary key");
        session.evict(a);
    }
}
tx.commit();
session.close();

hope this will solve your problem

Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
0

why are you evicting it from session? You can ignore it.
it will then save the successful object while iteration and leave the error one's.
Other way is you can flush the session once object is evicted in catch block.
Hope this may work

Alok
  • 301
  • 1
  • 6