CRUDRespository中的Update或SaveorUpdate,有没有可用的选项 [英] Update or SaveorUpdate in CRUDRespository, Is there any options available
问题描述
我正在尝试使用我的实体" Bean进行CRUD操作. CRUDRepository
为find
,delete
和save
提供标准方法,但是没有像saveOrUpdate(Entity entity)
这样的通用方法可用,它们又依次调用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 extends T> S save(S entity)
从界面
CrudRepository<T, ID extends Serializable> extends Repository<T, ID>
自动执行您想要的操作.如果实体是新实体,它将在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);
}
}
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屋!