【发布时间】:2019-04-30 17:46:10
【问题描述】:
我最近开始了一个使用 Spring Boot 的项目。我仍在学习一些概念,但与数据访问相关的一些事情让我有点困扰。让我举个例子。
我有几个实体:
@Entity
class Book {
@Id
private Long idBook;
private String title;
@ManyToOne
@JoinColumn(name = "idAuthor")
private Author author;
}
@Entity
class Author {
@Id
private Long idAuthor;
private String name;
@OneToMany(fetch = FetchType.LAZY)
private List<Book> books;
}
为了简单起见,假设一本书只能有一个作者。
图书存储库是一个简单的界面:
public interface BookRepository extends JpaRepository<Book, Long> {}
我也有书籍的 DTO:
class BookDTO {
private Long idBook;
private String title;
private idAuthor;
}
当客户想要保存一本书时,他会发送一个这样的 json:
{
"idBook":328,
"title":"The Martian Chronicles",
"idAuthor":56
}
每当有人需要保存一本书时,他会将 DTO 转换为实体并在保存前获取作者:
entityBook.setId(dtoBook.getId());
entityBook.setTitle(dtoBook.getTitle());
entityBook.setAuthor(authorRepository.getById(dtoBook.getIdAuthor()));
bookRepository.save(entityBook);
对我来说,这似乎是一种资源浪费,因为只需要保存 idAuthor。这是一个简单的例子。我面临的现实生活情况要复杂得多,有时会令人沮丧。
我使用 EntityManager::getReference 方法找到了解决方案。
persisting a new object without having to fetch the associations
Hibernate persist entity without fetching association object. just by id
问题(如果我没有理解错的话)是:在存储库之外获取 EntityManager 引用(通过 @PersistenceContext 注入)不是一个好习惯,并且从 dto 到实体的转换是在调用之前的层上进行的到存储库。
是否有其他方法可以在不访问上层的 EntityManager 的情况下完成此操作?
【问题讨论】: