本文介绍了如何告诉推土机在目标字段中使用LinkedHashSet集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在头等舱我有一个字段:

In first class i have field:

private Set<Country> countries;

public Set<Country> getCountries() {
    return countries;
}

public void setCountries(Set<Country> countries) {
    this.countries = countries;
}

将包含LinkedHashSet实现.

which will contain LinkedHashSet implementation.

在第二类中,我具有相同的声明,但是在映射过程中,Dozer在目标类中创建HashSet实现,这破坏了元素的顺序.如何告诉推土机在目标类中使用LinkedHashSet?

In second class i have identical declaration, but during mapping, Dozer creates HashSet implementation in destination class, which destroys the order of elements. How to tell Dozer to use LinkedHashSet in destination class?

推荐答案

推土机映射Set时,它将使用 org.dozer.util.CollectionUtils.createNewSet 创建目标Set实例.您得到HashSetTreeSet.

When Dozer maps a Set, it uses the org.dozer.util.CollectionUtils.createNewSet to create the destination Set instance. You get either a HashSet or TreeSet.

如果元素的顺序与其自然顺序相同,则可以使用 SortedSet 在目标位置.如果不是,那么您需要自己创建目标对象并提供所需的Set实现.

If the order of your elements is the same as their natural order you might use a SortedSet in the destination. If not, then you need to create the destination object yourself and provide the desired Set implementation.

推土机允许使用自定义的创建方法或自定义的 bean工厂可以实例化对象,而不是使用默认构造函数,因此可以使用以下任何一种方法:

Dozer allows using custom create methods or custom bean factories to instantiate objects beyond using the default constructor so you could use either method:

创建方法

Java代码:

public class MyInstanceCreator {
    public static DestinationObject createDestinationObject() {
        DestinationObject result = new DestinationObject();
        result.setCountries(new LinkedHashSet<Country>());
        return result;
    }
    private MyInstanceCreator() { }
}

映射:

<mapping>
    <class-a create-method="MyInstanceCreator.createDestinationObject">DestinationObject</class-a>
    <class-b>SourceObject</class-b>
    <field>
        <a>countries</a>
        <b>countries</b>
    </field>
</mapping>

豆工厂

Java代码:

public class MyBeanFactory implements BeanFactory {
    public Object createBean(Object source, Class<?> sourceClass, String targetBeanId) {
        DestinationObject result = new DestinationObject();
        result.setCountries(new LinkedHashSet<Country>());
        return result;
    }
}

映射:

<mapping>
    <class-a bean-factory="MyBeanFactory">DestinationObject</class-a>
    <class-b>SourceObject</class-b>
    <field>
        <a>countries</a>
        <b>countries</b>
    </field>
</mapping>

这篇关于如何告诉推土机在目标字段中使用LinkedHashSet集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 01:41
查看更多