3.3. Loading an object
Load an entity instance by its identifier value with the entity manager's
find()
method:
cat = em.find(Cat.class, catId); // You may need to wrap the primitive identifiers long catId = 1234; em.find( Cat.class, new Long(catId) );
In some cases, you don't really want to load the object state, but just having a reference to it (ie a proxy). You can get this reference using the
getReference()
method. This is especially useful to link a child to its parent without having to load the parent.
child = new Child(); child.SetName("Henry"); Parent parent = em.getReference(Parent.class, parentId); //no query to the DB child.setParent(parent); em.persist(child);
You can reload an entity instance and its collections at any time using the
em.refresh()
operation. This is useful when database triggers are used to initialize some of the properties of the entity. Note that only the entity instance and its collections are refreshed unless you specify REFRESH
as a cascade style of any associations:
em.persist(cat); em.flush(); // force the SQL insert and triggers to run em.refresh(cat); //re-read the state (after the trigger executes)