In Hibernate, get and load both are used for data retrieval
User user = (User) session.get(User.class, userID);
User user = (User) session.load(User.class, userID);
The identifier uniquely identifies a single instance of a class.
Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Difference in return value if record doesn't found
get() : Returns null if the object can’t be found.
load() : If can’t find the object in the cache or database, an exception is thrown. The load() method never returns null.
get() : Never returns a proxy.
load() : May return a proxy instead of a real persistent instance.
A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method.
Choosing between get() and load()
It's easy !
If you’re certain the persistent object exists, and non-existence would be considered exceptional, load() is a good option.
If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value for null.
Using load() has a further implication :
The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.