我发现管理此问题的唯一通用解决方案(在研究了定制转换器,事件监听器和代理解析器之后)是实现定制字段映射器。我在Dozer
API中发现了该功能(我不相信它在《用户指南》中有记录)。
一个简单的例子如下:
public class MyCustomFieldMapper implements CustomFieldMapper { public boolean mapField(Object source, Object destination, Object sourceFieldValue, ClassMap classMap, FieldMap fieldMapping) { // Check if field is a Hibernate collection proxy if (!(sourceFieldValue instanceof AbstractPersistentCollection)) { // Allow dozer to map as normal return false; } // Check if field is already initialized if (((AbstractPersistentCollection) sourceFieldValue).wasInitialized()) { // Allow dozer to map as normal return false; } // Set destination to null, and tell dozer that the field is mapped destination = null; return true; } }这会将所有未初始化的PersistentSet对象返回为null。我这样做是为了将它们传递给客户端时,我可以区分NULL(非加载)集合和空集合。这使我可以在客户端中定义通用行为,以使用预加载的集合,或进行另一个服务调用以检索集合(如果需要)。另外,如果您决定在服务层中急于加载任何集合,则它们将照常进行映射。
我使用spring注入自定义字段映射器:
<bean id="dozerMapper" lazy-init="false"> <property name="mappingFiles"> ... </property> <property name="customFieldMapper" ref="dozerCustomFieldMapper" /></bean><bean id="dozerCustomFieldMapper" />
我希望这对任何寻求解决方案的人有所帮助,因为我在搜索Internet时找不到任何示例。



