Java Spring Data JPA 更新方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32295688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:18:53  来源:igfitidea点击:

Spring Data JPA Update Method

javaspringspring-data-jpa

提问by MaxWell

I'm still looking for a update method in Spring's Data JPA to update a given Objectpersited in a relational database. I only found solutions in which I'm forced to specify some kind of UPDATE queries via @Query annotation (in comparison with @Modifying), for example:

我仍在寻找 Spring 的 Data JPA 中的更新方法来更新关系数据库中的给定对象。我只找到了强制通过@Query 注释指定某种 UPDATE 查询的解决方案(与 @Modifying 相比),例如:

@Modifying
@Query("UPDATE User u SET u.firstname = ?1, u.lastname = ?2 WHERE u.id = ?3")
public void update(String firstname, String lastname, int id);

For building the Query, I also have to pass single parameters instead of whole Objects. But that's exactly what I want to do (passing whole Objects).

为了构建查询,我还必须传递单个参数而不是整个 Objects。但这正是我想要做的(传递整个对象)。

So, what I'm trying to find is a method like this:

所以,我试图找到的是这样的方法:

public void update(Object obj);

Is it possible to build such a update method based on Spring Data JPA? How must it be annotated?

有没有可能基于Spring Data JPA构建这样的更新方法?它必须如何注释?

Thank you!

谢谢!

采纳答案by JB Nizet

If the goal is to modify an entity, you don't need any update method. You get the object from the database, modify it, and JPA saves it automatically:

如果目标是修改实体,则不需要任何更新方法。你从数据库中获取对象,修改它,JPA 自动保存它:

User u = repository.findOne(id);
u.setFirstName("new first name");
u.setLastName("new last name");

If you have a detached entity and want to merge it, then use the save() method of CrudRepository:

如果你有一个分离的实体并且想要合并它,那么使用 CrudRepository 的 save() 方法:

User attachedUser = repository.save(detachedUser);

回答by Ashutosh Srivastava

If you want to update an Entity you do not need JPQL query(Optional). You can directly use (old version)findOne or (new version) findById to access data and make required modifications

如果要更新实体,则不需要 JPQL 查询(可选)。您可以直接使用(旧版本)findOne 或(新版本)findById 来访问数据并进行所需的修改

Ex- here approve (entity ) is updated.

Ex- here批准(实体)被更新。

Optional<User> user= Repository.findById(id);
Registration reg = reg.get();       
reg.setApproved("yes");
userRepo.save(reg);

And That's It.

就是这样。