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);
}
}
call saveOrUpdate(a)
instead of session.save(a);
edit
start transaction
session.saveOrUpdate(a);
a.getId() // this should have id.
return a;
end transaction
As per your code I have not seen session.flush(); session.clear();
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
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
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.