CRUDRespository中的Update或SaveorUpdate,有没有可用的选项 [英] Update or SaveorUpdate in CRUDRespository, Is there any options available

查看:134
本文介绍了CRUDRespository中的Update或SaveorUpdate,有没有可用的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用我的实体" Bean进行CRUD操作. CRUDRepositoryfinddeletesave提供标准方法,但是没有像saveOrUpdate(Entity entity)这样的通用方法可用,它们又依次调用HibernateHibernateTemplate会话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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆