将实体集合映射到其ID的集合

时间:2015-05-03 16:57:18

标签: java dozer

我正在构建一个RESTful服务,我正在使用Dozer将我的JPA / Hibernate检索到的实体映射到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 entityBId:

<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配置。

1 个答案:

答案 0 :(得分:0)

  

但是如果我有一个带有一组EntityB对象的EntityA类,我就不能   将它映射到ids。

尝试将EntityBInteger映射。

<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 */
    }

然后,如果您有一个EntityA类,其中包含一组EntityB对象。您可以使用以下内容。

@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>