Home » Java » Hibernate: how to make the passed entity Persistent

Hibernate: how to make the passed entity Persistent

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have a method like below:

@Override
public <T extends Entity> T saveOrHibernateUpdate(T entity) {
    if (entity.getId() == null) {
        persist(entity);
    } else {
        getSession().update(entity);
    }
    return entity;
}

I want to use getSession().merge(entity) instead of getSession().update(entity) inside else condition.

But this method is already being used by other applications. To not effect others, the entity which is passed to this method should still remain persistent, how can I achieve this when I am using merge instead of update? Because merge will not make the passed entity as persistent. Any ideas?

Answers:

Hibernate merge() can be used to update values. Although this method creates a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked. So you can do the following:

@Override
public <T extends Entity> T saveOrHibernateUpdate(T entity) {
    if (entity.getId() == null) {
        persist(entity);
        return (T) entity;
    } else {
        Entity pEntity = (Entity) getSession().merge(entity);
        return (T) pEntity;
    }
}

By this way you will have the persistent object pEntity for many further manipulations.

Leave a Reply

Your email address will not be published. Required fields are marked *