Spring @Transactional merge and persist question
java, jpa, spring
Solution
This SO question is a good discussion of persist vs. merge, and the accepted answer explains it pretty well. The other answer also links to a good blog post about this.
According to the first reply in this other post, it sounds like it would be possible to call merge for both saving and updating an entity, but that's not how I've done it. In my Spring/JPA apps, I just have my DAOs extend JpaDaoSupport and use the getJpaTemplate() in the following way.
/**
* Save a new Album.
*/
public Album save(Album album) {
getJpaTemplate().persist(album);
return album;
}
/**
* Update an existing Album.
*/
public Album update(Album album) {
return getJpaTemplate().merge(album);
}
Problem
new to Spring and here @stackoverflow I'm building an stand-alone Inventory & Sales tracking app (Apache Pivot/Spring/JPA/Hibernate/MySQL) for a distributor business. So far I think everything is CRUD, so I plan to have a base class with everything @Transactional. Then I got a problem with my save generic method. Does persist and merge method of the EntityManager from Spring have a difference? I tried running and called the save for both inserting and updating and it worked fine(I think spring automatically refreshes the entity every time I call my save method // saw the hibernate queries being logged, is this right?). ``` @Transactional public abstract class GenericDAO { protected EntityManager em; // em getter+@PersistenceContext/setter public void save(T t) { // if (t.getId() == null) // create new // { // em.persist(t); // } else // update // { em.merge(t); // } } } ``` And btw, having a setup like this, I won't be much compromising performance right? Like calling salesDAO.findAll() for generating reports ( which does not need to be transactional, right? ). thanks!!!