This is probably more a “design” or style question: I have just been considering how complex a Hibernate transaction should or could be. I am working with an application that persists messages to a database using Hibernate.
Building the message POJO involves factoring out one-to-many relationships from the message into their respective persistent objects. For example the message contains a “city” field. The city is extracted from the message, the database searched for an equivalent city object and the resulting object added to the message POJO. All of this is done within a single transaction:
- Start transaction
- test for duplicate
- retrieve city object
- setCity(cityObject) in message object
- retreive country object
- setCountry(countryObject) in message object
- persist message object
- commit End transaction
In fact the actual transactions are considerably more complex. Is this a reasonable structure or should each task be completed within a single transaction (rather than all tasks in one transaction)? I guess the second question relates to best practice in designing the tasks within a transaction. I understand that some tasks need to be grouped for referential integrity, however this is not always the case.
Whatever you put within your outer transaction boundary, the question is whether you can successfully roll back each action.
Bundle related actions within a boundary, and keep it as simple as possible.