【问题标题】:Spring JPA - read a list of entities (with only partial properties) and update value without SELECTING the whole object from database?Spring JPA - 读取实体列表(只有部分属性)并更新值而不从数据库中选择整个对象?
【发布时间】:2021-09-27 12:33:53
【问题描述】:

我使用的是 Spring Boot 1.5.2。我有一个具有 多个属性 和多个 OneToMany 关系的大实体,例如:



@Entity
@Table(name = "person")
class Person {
   @Id
   protected long id;

   private String property1;
   private String property2;
   private String property3;
   private String property4;
   private String property5;
   private String property6;

   @OneToMany
   private List<Obj1> obj1List;
   @OneToMany
   private List<Obj2> obj2List;
   @OneToMany
   private List<Obj3> obj3List;
   @OneToMany
   private List<Obj4> obj4List;


}

如何从数据库中读取Person 的列表,但只有idproperty2 两个属性,并更新property2=0

然后,我可以使用 JPA CrudRepository 来保存():

public interface PersonRepository extends CrudRepository<Person, Long> {

}

for (Person person : personList) {
   this.personRepository.save(person)
}

我不想使用来自CrudRepositoryfindAll(),这使 Hibernate 能够在保存到数据库之前使用大 SQL 查询选择整个 Person 列表。

【问题讨论】:

  • 为什么还要获取、更新和保存。只需编写一个直接进行更新的方法即可。
  • @M.Deinum 当然,它需要先获取对象列表以更新属性,然后再保存到数据库。
  • 不,它没有。您只需编写一个更新查询即可完成所有这些操作,而无需检索所有内容。

标签: java spring-boot hibernate jpa


【解决方案1】:

在您的PersonRepository 界面中,您应该可以像这样添加Query

@Query("select new Person(id, property2) from Person")
List<Person> findIdAndProperty2();

其他字段应该返回 null,因为它们没有在您的查询中指定。您只需向Person 添加一个构造函数,并使用idproperty2 作为参数。

对于更新,您可以使用类似的语法...

@Modifying
@Query("update Person set property2 = ?1 where id in ?2")
int updateProperty2(String property2, List<Long> ids);

com.google.common.collect.Iterables.partition 可用于分块处理您的更新。比如……

for (List<Long> curUpdateIds : Iterables.partition(ids, 1000)) {
    personRepository.updateProperty2("0", curUpdateIds);
}

【讨论】:

  • 但在这里我想更新现有的人。我不确定 Hibernate 在更新对象之前是否仍会进行 SELECT 查询以获取此 Person 实体的所有属性(即使为 null)。
  • @BằngRikimaru 提出更新建议
猜你喜欢
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 2010-10-22
  • 1970-01-01
相关资源
最近更新 更多