users@glassfish.java.net

Re: EntityManager.refresh() How to save a DB trip?

From: <glassfish_at_javadesktop.org>
Date: Fri, 22 Aug 2008 11:39:15 PDT

You have to do the two trips because that's the way the system works.

Out of the box, the cache and the DB are supposed to be in sync.

user = (User)em.find(User.class, key)
This will hit the cache first, and if the object is there, never hit the DB.

user = (User)em.createNamedQuery("User.findByUserName").setParameter("userName", uName).getSingleResult();
This will hit the DB, but if the object is in the cache already, it will use that instead. This saves the overhead of marshalling the DB data in to a new entiy.

em.refresh(user)
This reloads the local entity from the DB.

You can force the Query always refresh, but you must use a Hint. A hint is an implementation specific note to the underlying JPA implementation. Toplink Essentials has a hint that forces a reload from the database for a specific query. The detail is that this hint won't port to another JPA implementation (though it will not hurt it either, you could specify multiple hints, and the underlying implementation will ignore the ones it doesn't understand).

Go read this: http://weblogs.java.net/blog/guruwons/archive/2006/09/understanding_t_1.html

It's a good discussion of how the TE cache system works, including the hints.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=294892