So I'm going to have to make a few educated guesses about what your methods are doing, because you haven't given us any details of what your service class and DAO is doing.
Firstly, marking your Service methods with @Transactional
is best practice, because your service class is the one that should be managing your transactional session. Your DAO should be only used for accessing the database and returning your objects in a form so you can use them. The session is not something the DAO should have to worry about.
Now I'm going to guess that your service class looks something like this:
@Transactional
public void saveOrUpdateFoo(Foo foo){
fooDao.saveOrUpdate(foo);
}
@Transactional
public Foo manipulateFoo(Foo foo){
//Do stuff to your Foo object that you want to be changed.
saveOrUpdateFoo(foo);
//Database hasn't actually changed yet.
foo = fooDao.findBy(foo.getFooId());
//nothing will change here.
}
To understand why your database doesn't actually change when you call saveOrUpdateFoo(foo)
, you need to understand what the @Transactional
annotation actually causes Hibernate too do. When you mark a method as @Transactional
you are telling Hibernate that everything inside this method, needs to happen in a single database session, and that it should be rolled back if something goes wrong.
To facilitate this, when you call currentSession().save(foo);
in your DAO (which I assume you are doing), Hibernate takes your object, and updates its local 'clone' of that object in memory. (This isn't actually how it works but just imagine that Hibernate keeps it's own copies of your objects based on the database when the transaction was started, when you call save/update it changes these copies)
When your @Transactional
method exits, Hibernate flushes these changes to the database which is when your database state actually changes. If this object is a new object (as in the database has to create a new record), Hibernate should update any ID fields that it manages when you call saveOrUpdateFoo
with the values that will be used when the database is saved. You shouldn't need to 're-fetch' your object once you have saved it, it should be in a state as if you had actually INSERT
'd it into the database, then SELECT
'd it again, without the changes actually being persisted to the database.
This shouldn't be a problem, unless you are trying to fetch the object from the database in another thread while all this is going on, in which case, you need to re-engineer your service class so that doesn't happen.
If this doesn't solve your problem, please post your service class and DAO, along with an explanation of what you are actually trying to do.