简体   繁体   中英

Hibernate calling get() after save() on the newly created record within the same transaction

I'm using hibernate 3.2.7 without spring (don't ask, client doesn't support spring) and I'm running into an issue with my implementation of the open-session-in-view pattern. When I persist an object to the database by calling save() I then call get() on that object to load the details of the child objects that are represented by foreign keys in the database . The problem is that when I call get() none of the child objects are being loaded. If I call the get() method from a new transaction everything loads as expected.

This is a snippet from my request filter that opens the session and creates the transaction:

HibernateUtil.openSession();

//get a transaction from JTA
transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");

transaction.begin();

// Call the next filter (continue request processing)
chain.doFilter(request, response);

// Commit and cleanup
log.finer("Committing the database transaction");
transaction.commit();

Here is a snippet from the service layer's save method that saves the transaction:

session.setFlushMode(FlushMode.MANUAL);

contract.save();

//save the update to the database
session.flush();

After the object is persisted the request gets passed to a struts action class that calls the get() method in the service which has this code to load the contract:

Session session = HibernateUtil.getSession();

session.setFlushMode(FlushMode.MANUAL);

try {

    contract = contract.get();

    ...
}

The same get action method is called when loading a persisted contract which works fine so I know the get() method works properly when isolated in its own transaction. The only time it doesn't work is when its called right after the save() from within the same transaction.

你试过对对象做一个Session.refresh()吗?

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