[英]Mapping a collection of entities to a collection of their Ids
我正在构建RESTful服务,正在使用Dozer将通过JPA /休眠检索到的实体映射到DTO,反之亦然。 让我们假设以下情况。 我有EntityA和EntityB类以及我的EntityADto和DTO。
@Entity
public class EntityA {
@GeneratedValue
@Id
private Integer id;
private EntityB entityB;
/* Getter & Setter */
}
@Entity
public class EntityB {
@GeneratedValue
@Id
private Integer id;
/* Getter & Setter */
}
public class EntityADto {
private Integer id;
private Integer entityBId;
/* Getter & Setter */
}
在这种情况下,我可以通过以下映射将EntityB类型的EntityB映射到我的Integer实体BId:
<mapping>
<class-a>EntityA</class-a>
<class-b>EntityADto</class-b>
<field>
<a>entityB.id</a>
<b>entityBId</b>
</field>
</mapping>
到目前为止,该方法有效。
但是,如果我有一个带有一组EntityB对象的EntityA类,则无法将其映射到ID。
@Entity
public class EntityA {
@GeneratedValue
@Id
private Integer id;
private Set<EntityB> entityBs;
/* Getter & Setter */
}
public class EntityADto {
private Integer id;
private Set<Integer> entityBIds;
/* Getter & Setter */
}
我宁愿避免使用自定义映射器,并尽可能使用XML配置。
但是,如果我有一个带有一组EntityB对象的EntityA类,则无法将其映射到ID。
尝试将EntityB
与Integer
映射。
<mapping>
<class-a>EntityB</class-a>
<class-b>Integer</class-b>
<field>
<a>entityBs.id</a>
<b>entityBIds</b>
</field>
</mapping>
这将导致以下Exception: org.dozer.MappingException: No read or write method found for field (entityBIds) in class (class java.lang.Integer)
我们无法使用XML映射Set<EntityB>
与Set<Integer>
,从而导致上述Exception
。
我宁愿建议如下更改您的DTO的模型,这对于设计也是一种很好的做法。
public class EntityADto {
private Integer id;
private EntityBDto entityBDto;
/* Getter & Setter */
}
public class EntityBDto {
private Integer id;
/* Getter & Setter */
}
然后,如果您有一个带有一组EntityB对象的EntityA类。 您可以使用以下内容。
@Entity
public class EntityA {
@GeneratedValue
@Id
private Integer id;
private Set<EntityB> entityBs;
/* Getter & Setter */
}
public class EntityADto {
private Integer id;
private Set<EntityBDto> entityBDtos;
/* Getter & Setter */
}
我建议更新DTO的模型,以便可以使用XML配置完成推土机映射。
<mapping>
<class-a>EntityB</class-a>
<class-b>EntityBDto</class-b>
<field>
<a>entityBs.id</a>
<b>entityBDtos.id</b>
</field>
</mapping>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.