spring-boot - 保存具有多个惰性关联的实体
问题描述
我有一个场景,我需要保存具有多个关联的实体,但如果不需要,我不想检索这些关联。
我将尝试举一个简单的例子:
实体:
public class Foo {
private Long idFoo;
private String defaultMessage;
/* Getters and Setters Ommited */
}
public class Bar {
private Long idBar;
private String message;
/*one-to-one lasy assoc*/
private Foo foo;
/* Getters and Setters Ommited */
}
条形输入 DTO
Public class BarInputDTO {
private String message;
@NotNull
private idFoo;
/* Getters and Setters Ommited */
}
服务坚持吧
public void saveAsEntity(BarInputDTO dto) {
Bar bar = new Bar();
//Getting a reference do foo
bar.setFoo(fooRepository.getOne(dto.getIdFoo()));
if (dto.getMessage().equals("")) {
/*
* I just want to load the association if there is no message.
* but get - LazyInitializationException: could not initialize proxy - no session
*/
bar.setMessage(bar.getFoo().getDefaultMessage());
} else {
bar.setMessage(dto.getMessage);
}
barRepository.save(bar);
}
正如评论所说,如果没有消息,我只想加载关联。但是在这种情况下,我得到了一个 LazyInitializationException。如果有消息通知 Bar 被保存。
我知道 fooRepository.getOne 在调用时打开和关闭事务,然后当我调用 getDefaultMessage 时没有会话。我认为在方法中添加@Transaction 注释可以解决问题,但我错了。
当然,我可以直接从 if 子句中的 fooRepo 获取 Foo 对象,但我的实际情况要复杂一些,而且这将是一项非常重复的任务。
有什么我想念的东西让它工作吗?
谢!
解决方案
推荐阅读
- python - 自动修复vscode中python代码中的间距错误
- python - 如何解决 Python 中的“无法连接 'str' 和 'list' 对象”?
- python - 对于大约 250 000 个模型的对象,Django 是否应该变得如此缓慢?
- angular - 使用 S3 预签名 url + MD5 校验和上传文件的问题
- c++ - 如果旧的 C++ 编译器没有实现 new 关键字,那么定义它是错误的吗?
- android - 如何减小使用 Jetpack Compose 构建的应用程序的大小?
- azure-cosmosdb - Cosmos DB Change Feed 的时间分辨率是多少?
- rust - 为什么 rust libc 对结构使用 repr(packed)?
- java - Spring Boot:无法映射 id 字段 [Reup]
- php - 如何调用子文件夹中的数据库文件?