简体   繁体   中英

Force Hibernate To Save A Specific POJO

I have some code calling a webservice and it returns an ID. I am saving this ID in the database using hibernate. I have a filter that opens the session and commits it, rolling back when any exception occurs within the contained code. Since there is no way to get back the ID returned by the webservice I would like to save this in the database EVEN if there is an exception that occurred later on in the code. Is there anyway to do this using the same session?

It depends on who throws the exception. If it is thrown by the hibernate session object you cannot reuse the session anymore as stated in hibernate Session documentation:

If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

If the exception is thrown by some other code, then yes, you can do something like this:

Long yourIdFromWebservice = ...

try {
   // do some processing that might result in an exception
}
catch(//the interesting exception, but not HibernateException) {
     //maybe log it, rethrow it
}
finally {
   session.save() //save what needed to be saved
}

or depending on your use case:

try {
   // do some processing that might result in an exception
   session.save() //save all stuff if no exception
}
catch(//the interesting exception, but not HibernateException) {
     session.save() //save only the id from the webservice
}

The right way to do that is to use two transactions: one to save the ID, and one to save the rest of your work.

If you're using EJB, you could do the save of the ID in a bean of its own, and annotate it with a TransactionAttribute of REQUIRES_NEW .

Otherwise, you can look at what control over transactions your environment gives you, and figure out a way to have two of them.

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