用于双向 Hibernate 关联的 MapStruct 自定义列表映射
MapStruct custom list mapping for bi-directional Hibernate association
执行从数据传输对象 (DTO) 到 Hibernate 实体的 MapStruct 映射的最佳方法是什么?定向一对多关联?
假设我们有一个 BookDto
链接了多个 ReviewDto
类型的评论:
public class BookDto {
private List<ReviewDto> reviews;
// getter and setters...
}
相应的 Hibernate 实体 Book
与 Review
:
具有一对多关联
@Entity
public class Book {
@OneToMany(mappedBy = "book", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Review> reviews = new ArrayList<>();
public void addReview(Review review) {
this.reviews.add(review);
review.setBook(this);
}
//...
}
@Entity
public class Review {
@ManyToOne(fetch = FetchType.LAZY)
private Book book;
public void setBook(Book book) {
this.book = book;
}
//...
}
请注意,本书的 addReview
方法通过调用 review.setBook(this)
来双向设置关联,正如 Hibernate 专家(例如 'Hibernate Tips: How to map a bi-directional many-to-one association' by Thorben Janssen or 'How to synchronize bidirectional entity associations with JPA and Hibernate' by Vlad Mihalcea)所推荐的那样,以确保域模型关系一致性。
现在,我们需要一个 MapStruct 映射器,它可以自动将评论链接回图书。
到目前为止,我发现了多个选项,每个选项都有一些缺点:
- 自定义映射方法:
@Mapper
public interface BookMapper {
default Book mapBookDtoToBook(BookDto bookDto) {
//...
for (ReviewDto reviewDto : bookDto.getReviews()) {
book.addReview(mapReviewDtoToReview(reviewDto));
}
//...
}
//...
}
如果书中有许多其他字段要映射,这会变得很麻烦。 [更新:这可以按照 的建议进行简化。 ]
- 在
@AfterMapping
方法中建立双向关系:
@Mapper
public interface BookMapper {
Book mapBookDtoToBook(Book book); // Implementation generated by MapStruct
@AfterMapping
void linkReviewsToBook(@MappingTarget Book book) {
for (Review review : book.getReviews()) {
review.setBook(book);
}
}
//...
}
这种方法允许 MapStruct 生成所有其他字段映射;但是通过将自动生成的 setReviews
与后映射中的 setBook
操作分离,我们失去了凝聚力。
- 在
Book
中添加方法setBiDirectionalReviews
并指示MapStruct将其用作目标:
@Entity
public class Book {
//...
public void setBiDirectionalReviews(List<Review> reviews) {
this.reviews = reviews;
for (Review review : this.reviews) {
review.setBook(this);
}
}
}
@Mapper
public class BookMapper {
@Mapping(source = "reviews", target = "biDirectionalReviews")
Book mapBookDtoToBook(Book book);
}
现在我们已经重新建立了凝聚力,但是 (1) 如果我们想在其他地方修改现有的评论,我们可能仍然需要额外的方法 addReview
,并且 (2) 滥用感觉有点老套MapStruct 的访问器命名策略假装有一个名为“biDirectionalReviews”的字段。
无论如何,这是迄今为止我能找到的最好的方法。
在MapStruct中映射双向关联是否有更好的解决方案?
您可以使用 abstract class
而不是 interface
来执行第一个选项。这样您就可以公开主要方法,同时仍然对除 Book
的 reviews
之外的所有映射使用 mapstruct。这也消除了需要手动映射其他字段的缺点,因为您可以使用辅助方法。
@Mapper
public abstract class BookMapper {
public Book map(BookDto dto) {
Book book = mapBook( dto );
for ( ReviewDto reviewDto : dto.getReviews() ) {
Review review = mapReview( reviewDto );
book.addReview( review );
}
return book;
}
// mapstruct annotations
@Mapping(target = "reviews", ignore=true) // if needed
abstract Book mapBook(BookDto dto);
// mapstruct annotations
@Mapping(target = "book", ignore=true) // if needed
abstract Review mapReview(ReviewDto reviewDto);
}
编辑:我认为 更好。
解决方案一,@Context
这个问题可以通过 @Context 解决。
Mapstruct 贡献者提供 example 如何在 JPA 的 parent/child 关系中使用 @Context
。
示例:
@Mapper
public interface JpaMapper {
JpaMapper MAPPER = Mappers.getMapper( JpaMapper.class );
Book toEntity(BookDTO s, @Context JpaContext ctx);
@Mapping(target = "book", ignore = true)
Review toEntity(ReviewDTO s, @Context JpaContext ctx);
}
public class JpaContext {
private Book bookEntity;
@BeforeMapping
public void setEntity(@MappingTarget Book parentEntity) {
this.bookEntity = parentEntity;
// you could do stuff with the EntityManager here
}
@AfterMapping
public void establishRelation(@MappingTarget Review childEntity) {
childEntity.setBook(bookEntity);
// you could do stuff with the EntityManager here
}
}
用法:
Book book = JpaMapper.MAPPER.toEntity(bookDTO, new JpaContext());
生成的代码:
public class JpaMapperImpl implements JpaMapper {
@Override
public Book toEntity(BookDTO s, JpaContext ctx) {
if ( s == null ) {
return null;
}
Book book = new Book();
ctx.setEntity( book );
book.setId( s.getId() );
book.setName( s.getName() );
book.setReviews( reviewDTOListToReviewList( s.getReviews(), ctx ) );
return book;
}
@Override
public Review toEntity(ReviewDTO s, JpaContext ctx) {
if ( s == null ) {
return null;
}
Review review = new Review();
review.setId( s.getId() );
review.setName( s.getName() );
ctx.establishRelation( review );
return review;
}
protected List<Review> reviewDTOListToReviewList(List<ReviewDTO> list, JpaContext ctx) {
if ( list == null ) {
return null;
}
List<Review> list1 = new ArrayList<Review>( list.size() );
for ( ReviewDTO reviewDTO : list ) {
list1.add( toEntity( reviewDTO, ctx ) );
}
return list1;
}
}
方案二,Collection mapping strategies
您可以为集合映射指定 CollectionMappingStrategy.ADDER_PREFERRED 策略。这意味着 Mapstruct 将使用 addReview(Review review)
方法将 Review
个对象添加到集合中。
我认为这是正确的解决方案。
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface JpaMapper {
JpaMapper MAPPER = Mappers.getMapper( JpaMapper.class );
Book toEntity(BookDTO s);
@Mapping(target = "book", ignore = true)
Review toEntity(ReviewDTO s);
}
生成的代码:
public class JpaMapperImpl implements JpaMapper {
@Override
public Book toEntity(BookDTO s) {
if ( s == null ) {
return null;
}
Book book = new Book();
book.setId( s.getId() );
book.setName( s.getName() );
if ( s.getReviews() != null ) {
for ( ReviewDTO review : s.getReviews() ) {
book.addReview( toEntity( review ) );
}
}
return book;
}
@Override
public Review toEntity(ReviewDTO s) {
if ( s == null ) {
return null;
}
Review review = new Review();
review.setId( s.getId() );
review.setName( s.getName() );
return review;
}
}
单元测试:
@Test
public void test() {
BookDTO bookDTO = new BookDTO();
bookDTO.setId(1L);
bookDTO.setName("Book 1");
ReviewDTO reviewDTO1 = new ReviewDTO();
reviewDTO1.setId(1L);
reviewDTO1.setName("Review 1");
ReviewDTO reviewDTO2 = new ReviewDTO();
reviewDTO2.setId(2L);
reviewDTO2.setName("Review 2");
List<ReviewDTO> reviewDTOS = Arrays.asList(reviewDTO1, reviewDTO2);
bookDTO.setReviews(reviewDTOS);
Book book = JpaMapper.MAPPER.toEntity(bookDTO, new JpaContext());
//Book book = JpaMapper.MAPPER.toEntity(bookDTO);
Assert.assertNotNull(book);
Assert.assertEquals(book.getId(), book.getId());
Assert.assertEquals(book.getName(), bookDTO.getName());
Assert.assertEquals(book.getReviews().size(), bookDTO.getReviews().size());
Assert.assertEquals(book.getReviews().get(0).getId(), bookDTO.getReviews().get(0).getId());
Assert.assertEquals(book.getReviews().get(1).getId(), bookDTO.getReviews().get(1).getId());
book.getReviews().forEach(review -> Assert.assertEquals(review.getBook(), book));
}
执行从数据传输对象 (DTO) 到 Hibernate 实体的 MapStruct 映射的最佳方法是什么?定向一对多关联?
假设我们有一个 BookDto
链接了多个 ReviewDto
类型的评论:
public class BookDto {
private List<ReviewDto> reviews;
// getter and setters...
}
相应的 Hibernate 实体 Book
与 Review
:
@Entity
public class Book {
@OneToMany(mappedBy = "book", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Review> reviews = new ArrayList<>();
public void addReview(Review review) {
this.reviews.add(review);
review.setBook(this);
}
//...
}
@Entity
public class Review {
@ManyToOne(fetch = FetchType.LAZY)
private Book book;
public void setBook(Book book) {
this.book = book;
}
//...
}
请注意,本书的 addReview
方法通过调用 review.setBook(this)
来双向设置关联,正如 Hibernate 专家(例如 'Hibernate Tips: How to map a bi-directional many-to-one association' by Thorben Janssen or 'How to synchronize bidirectional entity associations with JPA and Hibernate' by Vlad Mihalcea)所推荐的那样,以确保域模型关系一致性。
现在,我们需要一个 MapStruct 映射器,它可以自动将评论链接回图书。 到目前为止,我发现了多个选项,每个选项都有一些缺点:
- 自定义映射方法:
@Mapper
public interface BookMapper {
default Book mapBookDtoToBook(BookDto bookDto) {
//...
for (ReviewDto reviewDto : bookDto.getReviews()) {
book.addReview(mapReviewDtoToReview(reviewDto));
}
//...
}
//...
}
如果书中有许多其他字段要映射,这会变得很麻烦。 [更新:这可以按照
- 在
@AfterMapping
方法中建立双向关系:
@Mapper
public interface BookMapper {
Book mapBookDtoToBook(Book book); // Implementation generated by MapStruct
@AfterMapping
void linkReviewsToBook(@MappingTarget Book book) {
for (Review review : book.getReviews()) {
review.setBook(book);
}
}
//...
}
这种方法允许 MapStruct 生成所有其他字段映射;但是通过将自动生成的 setReviews
与后映射中的 setBook
操作分离,我们失去了凝聚力。
- 在
Book
中添加方法setBiDirectionalReviews
并指示MapStruct将其用作目标:
@Entity
public class Book {
//...
public void setBiDirectionalReviews(List<Review> reviews) {
this.reviews = reviews;
for (Review review : this.reviews) {
review.setBook(this);
}
}
}
@Mapper
public class BookMapper {
@Mapping(source = "reviews", target = "biDirectionalReviews")
Book mapBookDtoToBook(Book book);
}
现在我们已经重新建立了凝聚力,但是 (1) 如果我们想在其他地方修改现有的评论,我们可能仍然需要额外的方法 addReview
,并且 (2) 滥用感觉有点老套MapStruct 的访问器命名策略假装有一个名为“biDirectionalReviews”的字段。
无论如何,这是迄今为止我能找到的最好的方法。
在MapStruct中映射双向关联是否有更好的解决方案?
您可以使用 abstract class
而不是 interface
来执行第一个选项。这样您就可以公开主要方法,同时仍然对除 Book
的 reviews
之外的所有映射使用 mapstruct。这也消除了需要手动映射其他字段的缺点,因为您可以使用辅助方法。
@Mapper
public abstract class BookMapper {
public Book map(BookDto dto) {
Book book = mapBook( dto );
for ( ReviewDto reviewDto : dto.getReviews() ) {
Review review = mapReview( reviewDto );
book.addReview( review );
}
return book;
}
// mapstruct annotations
@Mapping(target = "reviews", ignore=true) // if needed
abstract Book mapBook(BookDto dto);
// mapstruct annotations
@Mapping(target = "book", ignore=true) // if needed
abstract Review mapReview(ReviewDto reviewDto);
}
编辑:我认为
解决方案一,@Context
这个问题可以通过 @Context 解决。
Mapstruct 贡献者提供 example 如何在 JPA 的 parent/child 关系中使用 @Context
。
示例:
@Mapper
public interface JpaMapper {
JpaMapper MAPPER = Mappers.getMapper( JpaMapper.class );
Book toEntity(BookDTO s, @Context JpaContext ctx);
@Mapping(target = "book", ignore = true)
Review toEntity(ReviewDTO s, @Context JpaContext ctx);
}
public class JpaContext {
private Book bookEntity;
@BeforeMapping
public void setEntity(@MappingTarget Book parentEntity) {
this.bookEntity = parentEntity;
// you could do stuff with the EntityManager here
}
@AfterMapping
public void establishRelation(@MappingTarget Review childEntity) {
childEntity.setBook(bookEntity);
// you could do stuff with the EntityManager here
}
}
用法:
Book book = JpaMapper.MAPPER.toEntity(bookDTO, new JpaContext());
生成的代码:
public class JpaMapperImpl implements JpaMapper {
@Override
public Book toEntity(BookDTO s, JpaContext ctx) {
if ( s == null ) {
return null;
}
Book book = new Book();
ctx.setEntity( book );
book.setId( s.getId() );
book.setName( s.getName() );
book.setReviews( reviewDTOListToReviewList( s.getReviews(), ctx ) );
return book;
}
@Override
public Review toEntity(ReviewDTO s, JpaContext ctx) {
if ( s == null ) {
return null;
}
Review review = new Review();
review.setId( s.getId() );
review.setName( s.getName() );
ctx.establishRelation( review );
return review;
}
protected List<Review> reviewDTOListToReviewList(List<ReviewDTO> list, JpaContext ctx) {
if ( list == null ) {
return null;
}
List<Review> list1 = new ArrayList<Review>( list.size() );
for ( ReviewDTO reviewDTO : list ) {
list1.add( toEntity( reviewDTO, ctx ) );
}
return list1;
}
}
方案二,Collection mapping strategies
您可以为集合映射指定 CollectionMappingStrategy.ADDER_PREFERRED 策略。这意味着 Mapstruct 将使用 addReview(Review review)
方法将 Review
个对象添加到集合中。
我认为这是正确的解决方案。
@Mapper(collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface JpaMapper {
JpaMapper MAPPER = Mappers.getMapper( JpaMapper.class );
Book toEntity(BookDTO s);
@Mapping(target = "book", ignore = true)
Review toEntity(ReviewDTO s);
}
生成的代码:
public class JpaMapperImpl implements JpaMapper {
@Override
public Book toEntity(BookDTO s) {
if ( s == null ) {
return null;
}
Book book = new Book();
book.setId( s.getId() );
book.setName( s.getName() );
if ( s.getReviews() != null ) {
for ( ReviewDTO review : s.getReviews() ) {
book.addReview( toEntity( review ) );
}
}
return book;
}
@Override
public Review toEntity(ReviewDTO s) {
if ( s == null ) {
return null;
}
Review review = new Review();
review.setId( s.getId() );
review.setName( s.getName() );
return review;
}
}
单元测试:
@Test
public void test() {
BookDTO bookDTO = new BookDTO();
bookDTO.setId(1L);
bookDTO.setName("Book 1");
ReviewDTO reviewDTO1 = new ReviewDTO();
reviewDTO1.setId(1L);
reviewDTO1.setName("Review 1");
ReviewDTO reviewDTO2 = new ReviewDTO();
reviewDTO2.setId(2L);
reviewDTO2.setName("Review 2");
List<ReviewDTO> reviewDTOS = Arrays.asList(reviewDTO1, reviewDTO2);
bookDTO.setReviews(reviewDTOS);
Book book = JpaMapper.MAPPER.toEntity(bookDTO, new JpaContext());
//Book book = JpaMapper.MAPPER.toEntity(bookDTO);
Assert.assertNotNull(book);
Assert.assertEquals(book.getId(), book.getId());
Assert.assertEquals(book.getName(), bookDTO.getName());
Assert.assertEquals(book.getReviews().size(), bookDTO.getReviews().size());
Assert.assertEquals(book.getReviews().get(0).getId(), bookDTO.getReviews().get(0).getId());
Assert.assertEquals(book.getReviews().get(1).getId(), bookDTO.getReviews().get(1).getId());
book.getReviews().forEach(review -> Assert.assertEquals(review.getBook(), book));
}