Srihari
Srihari

Reputation: 83

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

In my code, I did as follows:

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);
        }
    }
}

Upvotes: 5

Views: 3134

Answers (2)

Ophidian
Ophidian

Reputation: 10043

JPA tries very hard to be a helpful API, such that anything you get from it (or save to it) will subsequently be tracked by JPA. This means than any further changes will be automatically handled for you by JPA without any additional work on your part.

Upvotes: 1

Bozho
Bozho

Reputation: 597432

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"

Upvotes: 8

Related Questions