[英]Spring Data JPA: update a list of Entity using a list of input in a custom Query
I have the following basic objects:我有以下基本对象:
/* User class */
import lombok.Data;
import lombok.AllArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.Id
import javax.persistence.GeneratedValue;
import javax.persistence.ManyToOne;
@Data
@Entity
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String surname;
@ManyToOne
private Address address;
}
/* UserComposite class, used to load partial data from a user */
import lombok.Data;
import lombok.AllArgsConstructor;
@Data
@AllArgsConstructor
public class UserComposite {
private Long userId;
private String name;
private String surname;
}
My goal here, is to update a list of User using a list of UserComposite as input.我的目标是使用 UserComposite 列表作为输入来更新用户列表。 Here is what my DAO looks like:
这是我的 DAO 的样子:
/* UserDao class */
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
public interface UserDao extends JpaRepository<User, Long> {
@Transactional
@Modifying
@Query("update User u set u.name = uc.name , "
+ "u.surname = uc.surname "
+ "where u.id = uc.userId "
+ "and UserComposite uc in (?1)")
void updateUserFromCompositeList(List<UserComposite> userCompositeList);
}
However, this does not work.但是,这不起作用。 I have a hard time matching the data from the input with the data saved in my database, especially as UserComposite is not an entity.
我很难将输入中的数据与保存在我的数据库中的数据进行匹配,尤其是因为 UserComposite 不是实体。
Is there a way around this problem?有没有办法解决这个问题?
Update multiple rows with different ID
s values is not possible in one query.在一个查询中无法更新具有不同
ID
值的多行。
Update every user by id通过 id 更新每个用户
for (UserComposite user : List<UserComposite> userCompositeList) {
userDao.updateUser(user.getUserId(), user.getName(), user.getSurname());
}
Repository query like存储库查询如
@Modifying
@Query("UPDATE User u SET u.name = :name, u.surname = :surname WHERE u.id = :userId")
void updateUser(@Param("userId") int userId, @Param("name") String name, @Param("surname") String surname);
This looks contradictory to this post( https://self-learning-java-tutorial.blogspot.com/2019/09/spring-boot-jpa-update-query.html ) which I have tried and worked.这看起来与我尝试过的这篇文章( https://self-learning-java-tutorial.blogspot.com/2019/09/spring-boot-jpa-update-query.html )相矛盾。
can you please explain me bit more @eklavya你能解释一下吗@eklavya
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.