【问题标题】:How convert collection of id to collection of beans?如何将 id 集合转换为 bean 集合?
【发布时间】:2017-12-24 13:34:03
【问题描述】:
我有一些问题。
我有两个实体和一个 DTO。
@Entity
class X {
@OneToMany
Set<Y> set;
}
@Entity
class Y {
Long id;
@ManyToOne
X x;
}
class XDTO {
Set<Long> yId;
}
在那种情况下如何实现映射器?
@Mapper
public mapper() {
XDTO toDto (X x);
X toEntity (XDTO xDTO);
}
【问题讨论】:
标签:
java
entity
mapstruct
【解决方案1】:
根据您的描述,您似乎想要实现此目标:
- 在传递 X 实体时返回 XDTO,并且,
- 通过 XDTO 时返回 X 实体。
我想出了以下解决方案:
public Mapper{
// Returns XDTO when X entity is passed as a parameter
XDTO toDto(X x){
XDTO temp=new XDTO();
for(Y y: x.set){
temp.add(y.id)
}
return temp;
}
// Returns X entity when XDTO is passed as a parameter
X toEntity (XDTO xDTO){
Set<Y> tempSet=new HashSet<Y>();
for(Long yId:x.set){
Y ytemp=new Y();
ytemp.setId(yId);
tempSet.add(ytemp);
}
return tempSet;
}
}
【解决方案2】:
这样的事情应该可以工作:
@Mapper(uses=EntityMapper.class)
public interface XMapper() {
@Mapping(source="set", target="yId")
XDTO toDto (X x);
@InheritInverseConfiguration
X toEntity (XDTO xDTO);
}
public class EntityMapper {
EntityManager em = ...;
public <T extends BaseEntity> T resolve(long id, @TargetType Class<T> entityClass) {
entityManager.find( entityClass, id );
}
public long toReference(BaseEntity entity) {
return entity != null ? entity.getId() : null;
}
}