Hibernate SpringDataJPA如何检查是执行更新还是保存?
SpringDataJPA只包含save方法,而hibernate则有save和update方法。因此,spring data jpa如何检查是否更新或保存当前对象。spring data自动检测应该创建或更新的内容。 保存方法的源代码,例如在SimpleParepository(ImplementCrudepository)中,以防您的实体实现持久化Hibernate SpringDataJPA如何检查是执行更新还是保存?,hibernate,spring-data-jpa,Hibernate,Spring Data Jpa,SpringDataJPA只包含save方法,而hibernate则有save和update方法。因此,spring data jpa如何检查是否更新或保存当前对象。spring data自动检测应该创建或更新的内容。 保存方法的源代码,例如在SimpleParepository(ImplementCrudepository)中,以防您的实体实现持久化 public <S extends T> S save(S entity) { if (entityInformation.
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
对于Spring数据,JPA的“保存”用于更新和保存,甚至用于向表中添加新行
@Transactional
public void UpdateStudent(Student student) {
this.studentRepository.save(student);
}
例如,此方法保存当前现有的学生对象及其所有已更改的属性(如果有),或者如果学生对象实例是新实例,则将其插入表中
使用@Transactional注释,一旦方法退出,它就会将实例刷新到表中
由于主键是不可变的,Spring data JPA可以执行保存和更新(两者相同)以及插入新行。参考文档对此进行了详细描述。来自 保存实体可以通过 CrudRepository.save(…)-Method。它将保留或合并给定的 使用底层JPA EntityManager的实体。如果实体没有 虽然Spring数据已被持久化,但JPA将通过调用保存实体 entityManager.persist(…)方法,否则 将调用entityManager.merge(…)方法 Spring Data JPA提供以下策略来检测实体是否为新实体:
很明显,这并没有回答OP,OP是如何检查Spring数据是否更新或保存当前对象的。而是回答,
Spring Data JPA保存或更新对象的功能。
@Transactional
public void UpdateStudent(Student student) {
this.studentRepository.save(student);
}