CRUDRespository 中的 Update 或 SaveorUpdate,是否有可用的选项 [英] Update or SaveorUpdate in CRUDRespository, Is there any options available
问题描述
我正在尝试使用我的实体 bean 执行 CRUD 操作.CRUDRepository
提供了find
、delete
和save
的标准方法,但没有像saveOrUpdate 这样的通用方法可用(实体实体)
依次调用 Hibernate
或 HibernateTemplate
会话 saveorUpdate()
方法.
I am trying to do CRUD operations with My Entity bean. CRUDRepository
provide standard methods to find
, delete
and save
but there is no generic method available like saveOrUpdate(Entity entity)
that in turn calls Hibernate
or HibernateTemplate
sessions saveorUpdate()
methods.
CRUDRepository
提供此功能的方式是像这样使用
The way CRUDRepository
provides this functionality is to
use like this
@Modifying
@Query("UPDATE Space c SET c.owner = :name WHERE c.id = :id")
Integer setNameForId(@Param("name") String name, @Param("id")
但这不是通用的,需要为完整的表单字段编写.请让我知道是否有任何方法或者我可以获得 Hibernate 会话或 Spring HibernateTemplate 对象来解决这个问题.
but this is not generic and needs to be written for complete form fields. Please let me know if there is any way or i can get session of Hibernate or object of Spring HibernateTemplate to solve this issue.
推荐答案
方法的实现
S保存(S实体)
来自界面
CrudRepository
自动执行您想要的操作.如果实体是新的,它将调用 entity manager
上的 persist
,否则它将调用 merge
automatically does what you want. If the entity is new it will call persist
on the entity manager
, otherwise it will call merge
代码如下:
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
并且可以找到 此处.请注意,SimpleJpaRepository
是在 Spring Data JPA 中自动实现 CrudRepository
的类.
and can be found here. Note that SimpleJpaRepository
is the class that automatically implements CrudRepository
in Spring Data JPA.
因此,无需提供自定义的 saveOrUpdate()
方法.Spring Data JPA 已满足您的需求.
Therefore, there is no need to supply a custom saveOrUpdate()
method. Spring Data JPA has you covered.
这篇关于CRUDRespository 中的 Update 或 SaveorUpdate,是否有可用的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!