简体   繁体   English

如何使用spring CrudRepository更新属性?

[英]How to update an attribute with spring CrudRepository?

How can I create update methods in spring CurdRepository ? 如何在Spring CurdRepository创建update方法?

Something like: 就像是:

interface PersonRepository extends CrudRepository<PersonEntity> {
   //update ... set age =: age where name =: name
   boolean setAgeByName(age, name);
}

If you ask me: do not use such queries. 如果您问我:请勿使用此类查询。 That's because your second level cache gets eradicated and you get some performance problems (your application will be slightly slower). 那是因为您的二级缓存已被删除,并且您遇到了一些性能问题(您的应用程序会稍微慢一些)。

And by the way the process you want to do is in reality the following: 顺便说一下,实际上您要执行的过程如下:

  • you load your entity from the database 您从数据库加载实体
  • change the attribute on the loaded object (via a setter method) 更改已加载对象的属性(通过setter方法)
  • you save your entity to the database (this is done automagically when your transaction ends so you do not need to call PartnerRepository.save(entity) explicitly) 您可以将实体保存到数据库(这在事务结束时自动完成,因此您无需显式调用PartnerRepository.save(entity)

If you want to use a query then I suggest you write your query as you mentioned in your question: 如果您想使用查询,那么我建议您按照问题中的说明编写查询:

@Modifying
@Query("update Person p set p.age = :age where p.name = :name")
int setAgeByName(@Param("age") int age, @Param("name") String name);

And you get back how many entries have been modified. 您将获得修改了多少个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM