Although not the only or easiest way to do things, hibernate works very well in a transaction isolated situation like transaction managed EJB's.
The example below is a simple way to perform the operation with EJB 3 and an application server
(http://docs.oracle.com/javaee/5/tutorial/doc/bncij.html for detailed explaination)
Code:
@Stateless
public class MyStuffService {
@PersistenceContext
EntityManager entityManager;
/* This line isn't strictly needed unless you're also modifying the contents of myQueriedStuff */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Stuff getMyStuff() {
/* Do your DB queries in here */
return myQueriedStuff;
}
/* REQUIRES_NEW not strictly necessary */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void saveMyCurrentStuff(Stuff myCurrentStuff) {
entityManager.merge(myCurrentStuff);
/* .flush() not necessary because entityManager will be flushed automatically by the container manged transaction scaffolding in the application server */
}
}
class MyWebTier {
/* The application server will automatically create or use an instance of MyStuffService to service the calls using JNDI and/or CDI, but all you should care about is that you have an instance */
@EJB
MyStuffService service;
public void save(Stuff stuff) {
service.save(stuff);
}
public Stuff getLatestStuff() {
return service.getMyStuff();
}
}
In this way, when you leave the method (and your application server is setup correctly) your service will return a 'detached' copy of the query results. The detached part is important. If you modify 'myQueriedStuff' while it is still attached to hibernate, a .flush() call to hibernate will take all outstanding changes to the code and save them back to the DB.
I've always worked in transaction blocks with EJB's because its safer and more predictable. I'm not sure if you're using an appserver/stand-alone/or just servlet container, but depending on your environment, it can be a lot simpler to enforce certain behaviours. EJB is great because it gives you a nice simple isolation boundary between things happening in the backend/DB vs. the front end web tiers, which should ideally not know or care about the 'heavy lifting' being done in its stead.