Reputation: 272
Spring data jpa contains only save method unlike hibernate where we have save as well as update method. So how spring data jpa checks whether to update or save the current object .
Upvotes: 10
Views: 7889
Reputation: 12552
Spring data JPA saves a new entity and updates an old entity. Spring data JPA offers the following strategies to detect whether an entity is new or not.
From the docs .
Saving an entity can be performed via the CrudRepository.save(…)-Method. It will persist or merge the given entity using the underlying JPA EntityManager. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.persist(…) method, otherwise the entityManager.merge(…) method will be called.
Upvotes: 7
Reputation: 5407
spring data detect automatically what should be create or update. Source code for save method in for example in SimpleJpaRepository (implement CrudRepository) in case if your entity implements Persistable
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
so , there is a check what to do with entity save it or update based on if entity is new - then save it. is new check it's just check that id not null
for exaple if an entity implements Persistable :
public boolean isNew() {
return null == getId();
}
Upvotes: 2
Reputation: 83081
The reference documentation describes that in detail here.
Upvotes: 0
Reputation: 1149
With Spring data JPA 'save' is for both update and save, and even for adding a new row to a table.
@Transactional
public void UpdateStudent(Student student) {
this.studentRepository.save(student);
}
For example this method saves the current existing student object with all its changed properties (if any) or if the student object instance is a new one then it will be inserted into the table.
With the @Transactional annotation as soon as the method exits it flushes the instance to the table.
Spring data JPA is able to do both save and update (which are the same) and also inserting a new row since the primary key is immutable.
Upvotes: 0