I am porting my Dao layer from KodoJDO to Hibernate.
I am keeping my menus in the database and based on a user’s entitlements I prune a local copy to display only what the user is allowed to do.
When I did this in KodoJDO I had to make the objest I was pruning transient because I didn’t want to write the changes back to the db.
I don’t see any equivalent function in Hibernate. Is there one? How do I keep these changes from getting written back to the db.
Here is the prune function.
public void prune(Collection<Entitlement> ents)
{
Session session=PersistenceManager.getManager();
// Rewrite----------------------------------
//session.makeTransient(this);
for (Iterator<Leaf> iter = leafs.iterator(); iter.hasNext();)
{
Leaf l = (Leaf) iter.next();
if(!l.isAllowed(ents))
{
iter.remove();
}
}
for (Iterator<Branch> iter = branches.iterator(); iter.hasNext();)
{
Branch b = (Branch) iter.next();
if(b!= this)
{
b.prune(ents);
}
if (b.hasNoChildren())
{
iter.remove();
}
}
}
Comment on answers. I accepted the one that was most complete, but the answers by skaffman and Affe were valuable as well.
In JPA 2.0 it’s
entityManager.detach(..). I’m explicitly giving the JPA version, because it is advisable to use hibernate through JPA.If we look how is the
detach(..)method implemented in hibernate’sEntityManagerImpl, it uses thegetSession().evict(entity)on the underlying sessionBut note that you should rarely need to do this. I don’t know whether it’s a common practice in JDO, but in JPA/Hibernate it is not needed if you are using them properly.
As per your comment – if you want to use the hibernate entities as objects whose values you change but do not persist. I haven’t used them like that, because I usually don’t have an open session / entity manager in my view. Or I use value objects. If you both have an open session in the view, and you don’t have value objects – yes, this is a valid usage.