Hibernate Transaction

Simple Hibernate question.

If i was within a transaction, when will hibernate throw errors if there are database conflicts.

Is it only on commit? or does hibernate do any fancy checking when you do a .save() .update()?
LVL 2
dboyd6868Asked:
Who is Participating?
 
objectsCommented:
would think it would be only on commits
0
 
Dejan PažinHead of SW DevelopmentCommented:

Some errors will be thrown at method call time. You can see that from the specification of the methods. E.g. update method comment says:

/**
       * Update the persistent instance with the identifier of the given detached
       * instance. If there is a persistent instance with the same identifier,
       * an exception is thrown. This operation cascades to associated instances
       * if the association is mapped with <tt>cascade="save-update"</tt>.
       *
       * @param object a detached instance containing updated state
       * @throws HibernateException
       */

I dont know if that's fancy though :)
0
 
Jim CakalicSenior Developer/ArchitectCommented:
The Session will periodically execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process is called flushing. It occurs by default at several points: before some query executions, when Transaction.commit() is called, or when Session.flush() is called.

According to the Hibernate reference, except when you explicity flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale data; nor will they return the wrong data.

It is possible to change the default behavior so that flush occurs less frequently using Session.flushMode(..). The FlushMode class defines three different modes: only flush at commit time (and only when the Hibernate Transaction API is used), flush automatically using the explained routine, or never flush unless flush() is called explicitly. The last mode is useful for long running units of work, where a Session is kept open and disconnected for a long time.

In writing Hibernate Repository (or DAO) classes, I've found it sometimes helpful to explicitly flush at certain points so any SQLExceptions (constraint or primary key violations for example) happen closer to the point in the code where persistent object state is changing.

For more details and code examples, please refer to
http://www.hibernate.org/hib_docs/reference/en/html/objectstate.html

Regards,
Jim Cakalic
0
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.