Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring+JPA+Hibernate: persist is updating the entity surprisingly. Please go through the details

In my code, I did as follows:

  • queried for a course entity
  • populate it with the given course data.
  • courseDao.update(entity) which internally calls persist(entity) method.
  • Surprisingly, the data is got updated successfully.

I am confused with this behaviour of persist method.

Please help me out.

code is as below:

//My Service......
@Service("myService")
@Transactional
public class MyServiceImpl implements MyService {

  @Transactional(rollbackFor = { Throwable.class })
  public void updateCourse(final Course course) throws MyServiceException {
    ------
    ------
    CourseEntity courseEntity = courseDao.findById(course.getId());
    populateCourseEntity(courseEntity, course);

    courseDao.update(courseEntity);
  }
}

//CourseDao.....

public class CourseDaoImpl implements CourseDao {
   --------
   public void update(final T entity) throws MyDaoException {
        if (entity != null) {
            this.entityManager.persist(entity);
        }
        else {
            String errMsg = "Object to be updated cannot be null.";
            throw new MyDaoException(errMsg);
        }
    }
}
like image 720
Srihari Avatar asked Feb 05 '10 13:02

Srihari


People also ask

How do you resolve a detached entity passed to persist?

The solution is simple, just use the CascadeType. MERGE instead of CascadeType. PERSIST or CascadeType.

How do I update entity in JPA?

In this example you will learn how to update an entity object in JPA. We use the EntityManager. merge() method to update an entity. This method takes the entity to be saved as the parameter and return the merged entity back as the result.

What is the difference between Save () and persist () method in hibernate?

The save() method provides an identifier with the intent of an insert query being executed immediately for getting the identifier. It does not matter whether it is outside or inside a transaction. The persist() method fails to execute a given insert query in case it is placed outside transaction boundaries.


1 Answers

When an entity is currently managed (attached to a session), all updates to it are directly reflected to the underlying storage even without calling persist().

In your case, you load your entity, so it's in the session. Then even if you don't call persist() it will be updated in the database on transaction commit.

The persist() description from the javadoc:

Make an entity instance managed and persistent.

This means that the method doesn't do anything in your case, since your entity is both persistent and managed.

P.S. Where I say "session", understand "entity manager"

like image 137
Bozho Avatar answered Oct 23 '22 09:10

Bozho