简体   繁体   English

Spring Data JPA更新方法

[英]Spring Data JPA Update Method

I'm still looking for a update method in Spring's Data JPA to update a given Object persited in a relational database. 我仍然在寻找Spring的Data JPA中的更新方法来更新在关系数据库中持久存在的给定Object 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: 我只找到了解决方案,我不得不通过@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 . 为了构建Query,我还必须传递单个参数而不是整个对象 But that's exactly what I want to do (passing whole 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? 是否可以基于Spring Data JPA构建这样的更新方法? How must it be annotated? 它必须如何注释?

Thank you! 谢谢!

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);

If you want to update an Entity you do not need JPQL query(Optional). 如果要更新实体,则不需要JPQL查询(可选)。 You can directly use (old version)findOne or (new version) findById to access data and make required modifications 您可以直接使用(旧版本)findOne或(新版本)findById来访问数据并进行必要的修改

Ex- here approve (entity ) is updated. 此处批准(实体)已更新。

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

And That's It. 就是这样。

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

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