gpt4 book ai didi

java - JpaRepository getOne() 获取并更新整个对象

转载 作者:行者123 更新时间:2023-12-03 22:59:58 25 4
gpt4 key购买 nike

我正在尝试模仿这个已接受的 SO 答案
https://stackoverflow.com/a/39746931/3214777在仅更新某些对象的字段时使用 Hibernate 代理。
我的代码看起来像:

  @Transactional
public void updateStudentYear(int uniqueNumber, int newYear) {
Student studentProxy = studentRepository.getOne(uniqueNumber);
studentProxy.setYear(newYear);
studentRepository.save(studentProxy);
}
问题是 Hibernate 做了 全选和一个 完整更新 .这是日志:

2021-03-10 20:24:23.240 DEBUG 118757 --- [ main] org.hibernate.SQL : select student0_.unique_number as unique_n1_1_0_, student0_.name as name2_1_0_, student0_.team as team3_1_0_, student0_.year as year4_1_0_ from students student0_ where student0_.unique_number=?


2021-03-10 20:24:23.268 DEBUG 118757 --- [ main] org.hibernate.SQL : update students set name=?, team=?, year=? where unique_number=?


我原以为只会发出一个“ 更新年份”声明,但令我惊讶的是,看起来一切都像经典的 findOne()/save() 对操作那样完成。我错了吗?

最佳答案

不,不幸的是,链接问题中的答案是错误的。 getOne()/getReference()方法不是要更新单个字段,而是要避免访问数据库,除非需要。
该方法的用处是在以下情况下

Foo foo = fooRepo.findOne(id);
Bar barProxy = barRepo.getOne(id);
foo.setBar(barProxy);
fooRepo.save(foo);
在这种情况下 Foo将从数据库中获取,但 Bar将不会。
JPA 将始终更新更新语句中的所有字段,尽管我不确定它是否会受到实现自己的影响 dirty checking . Hibernate 有 @DynamicUpdate这限制了列,但 JPA 没有为其指定一般机制。

关于java - JpaRepository getOne() 获取并更新整个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66570808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com