我尝试使用 Dozer 将我的域实体转换为 DTO 对象。 所以,我想将 PersistentList、PersistentBag、...从我的域实体转换为 ArrayList、...在我的 DTO 对象中以避免惰性问题。
这是我的两个域实体的示例:
public class User {
private Collection<Role> roles;
...
}
public class Role {
private Collection<User> users;
...
}
我的 DTO 对象是相同的,只是类是 DTO 类型。因此,要将域转换为 DTO 对象,我使用以下 Dozer 映射:
<configuration>
<custom-converters>
<converter type=com.app.mapper.converter.BagConverter">
<class-a>org.hibernate.collection.PersistentBag</class-a>
<class-b>java.util.List</class-b>
</converter>
</custom-converters>
</configuration>
<mapping>
<class-a>com.app.domain.User</class-a>
<class-b>com.app.dto.UserDTO</class-b>
</mapping>
<mapping>
<class-a>com.app.domain.Role</class-a>
<class-b>com.app.dto.RoleDTO</class-b>
</mapping>
BagConverter 是一个 Dozer 自定义转换器,它的代码如下:
public class BagConverter<T> extends DozerConverter<PersistentBag, List>{
public BagConverter() {
super(PersistentBag.class, List.class);
}
public PersistentBag convertFrom(List source, PersistentBag destination) {
PersistentBag listDest = null;
if (source != null) {
if (destination == null) {
listDest = new PersistentBag();
} else {
listDest = destination;
}
listDest.addAll(source);
}
return listDest;
}
public List convertTo(PersistentBag source, List destination) {
List listDest = null;
if (source != null) {
if (destination == null) {
listDest = new ArrayList<T>();
} else {
listDest = destination;
}
if (source.wasInitialized()) {
listDest.addAll(source);
}
}
return listDest;
}}
因此,我得到了一个包含具有角色的 PersistentBag 的用户对象。我在该对象上应用 dozer mapper map 以获得 UserDTO 对象。我获得的结果是一个带有 Role 的 ArrayList 的 UserDTO 对象,但没有像我希望的那样有一个 RoleDTO 的 ArrayList。
我以为即使我使用自定义转换器,dozer 也会转换我列表的内容。这不是正确的方法吗?如果不是,如何通过将持久集合替换为经典 Java 集合来将我的域实体转换为 dto 对象?
感谢您的帮助。
西尔万。
最佳答案
不幸的是,当您注册 CustomConverter
时,您将承担映射对象(在您的情况下为集合)的全部责任,包括其所有内容、属性、元素等。
如我现在所见(我以前没有看到,它必须是某种新功能)。有可能使用 MapperAware
接口(interface),如 chapter for Custom Type Converters in Dozer docs 末尾所述.我想这正是满足您需求的方法。
关于java - Hibernate 对象到 DTO 的推土机映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2826313/