I\'m considering spring data for a project. Is it possible to override the per default generated save method? And if yes, how?
This could be helpful if you are going to reuse the original method. Just inject EntityManager
in the implementing class.
public interface MyEntityRepositoryCustom {
S save(S entity);
}
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom {
// optionally specify unitName, if there are more than one
@PersistenceContext(unitName = PRIMARY_ENTITY_MANAGER_FACTORY)
private EntityManager entityManager;
/**
* @see org.springframework.data.jpa.repository.support.SimpleJpaRepository
*/
@Transactional
public S save(S entity) {
// do your logic here
JpaEntityInformation entityInformation = JpaEntityInformationSupport.getMetadata(MyEntity.class, entityManager);
if (entityInformation.isNew(entity)) {
entityManager.persist(entity);
return entity;
} else {
return entityManager.merge(entity);
}
}
}