java - Entity in OneToMany collection is not updated
问题描述
Assume the following model:
@Entity
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<B> bs;
public B getB(long id) {
for(B b : bs)
if(b.getId() == id) {
return b;
}
}
}
@Entity
public class B {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "a_id")
private A a;
private String someString;
}
I then try to update a property of some entity B :
@Transactional(rollbackFor = Exception.class)
public void doSomeWork() {
A a = aRepository.findById(/* some id */);
a.getB(/* */).setSomeString(/* some string */);
}
When the method returns, I expect the modified entity B to be updated (SQL UPDATE). For some reason, it doesn't happen. I suspect that the framework is only aware about additions/removals to the bs
collection, but since every instance in the collection should be a managed entity, the framework should be aware of the changes.
Not sure what I'm missing here.
EDIT:
I created a repository to reproduce the issue:
https://github.com/mikomarrache/hibernate-spring-issue
If you comment lines 25-27 of the MyServiceImpl
class, the save in line 22 is performed. However, if you uncomment these lines, it looks like the save in line 22 is ignored but the second save in line 27 is done, and of course it breaks the unique constraint on name. In order to test, simply run the unit test. No need to populate the database, there is an SQL script on the classpath that is executed at startup.
解决方案
推荐阅读
- java - Java 的 gradle 构建问题:10.0.2,Gradle:4.7
- powershell - Get-AzureDeployment 未返回预期结果
- flask - Flask requests.args 在新的应用程序路由中保持变量
- version - 在运行 Web 应用程序中动态获取 Vaadin Flow 的版本
- javascript - 从 Polygon 获取图钉详细信息列表
- spring-boot - 如何将spring boot配置文件bootstrap.yml移出资源包
- java - Java String.format() 前导零和 1 个小数位
- ios - 进出后台时是否应禁用/重新启用 Firebase“keepSynced”?
- react-native - 在 React Native 中获得完整 ICU + CLDR 支持的最佳方式是什么?
- sql - 具有非唯一 ID 的分层查询