集合映射

| 假设我有以下课程:
class A1 {
  List<B1> bList;
}

class B1 {
  Long id;
}

---

class A2 {
  List<Long> bList;
}
我想用推土机将类A1映射到A2,其中A1.bList包含B1对象,而A2.bList仅包含B1对象的ID。 映射看起来如何? 谢谢。     
已邀请:
我认为您可以尝试为
Long
B1
建立映射。如果我没记错的话,这只是一种方法,我不记得那是哪种方法。抱歉,希望对您有所帮助。     
您可以使用推土机定制转换器。推土机客户转换器 示例:(可能的错误,未编译或测试)
<mapping>
  <class-a>A1</class-a>
  <class-b>A2</class-b>    
  <field custom-converter=\"converters.YourCustomConverter\">
    <a>bList</a>
    <b>bList</b>
  </field>
</mapping>
自定义转换器:
public class YourCustomConverter implements CustomConverter {

    public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
        if (source == null) {
            return null;
        }
        if (source instanceof List<?>) {
            List<?> list = ((List<?>) source);
            if (list.isEmpty()) {
                return null;
            }
            if (list.get(0) instanceof B1) {
                List<Long> longList = new ArrayList<Long>();
                for (B1 b1 : list) {
                    longList.add(b1.getId());
                }
                return longList;
            } else (list.get(0) instanceof Long) {
                // do the inverse of the above
            } else {
                throw new MappingException(\"Wrong type ...\");
            }
        } else {
            throw new MappingException(\"Converter YourCustomConverter used incorrectly. Arguments passed in were:\"
                    + destination + \" and \" + source);
        }
    } 
}
    
我认为您可以通过重写B1中的toString()方法来做到这一点,并且可以正常工作。 这是示例代码:
@Override
public String toString() {
return new String(this.id);
}
并在映射中进行以下更改:
<field>
 <a>bList</a>
 <b>bList</b>
 <a-hint>B</a-hint>
 <b-hint>java.lang.Long<b-hint>
</field>  
因此,当推土机尝试绑定B1时,它将返回其id为String,然后推土机将在String和Long之间执行自动转换。     

要回复问题请先登录注册