当实体具有多对一关系时,DTO到实体映射

时间:2017-11-15 18:43:50

标签: java hibernate orm mapping

我试图将业务对象映射到实体但却陷入困境,并且不知道如何解决这个问题。

问题是当我尝试从DTO映射这些属性时,这些属性是与另一个表的多对一关系的属性。

以下是我Entity的样子:

@Entity
@Table(name = "t_car")
public class Car extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdCar")
private Long id;

@Column(nullable = false, columnDefinition="VARCHAR(45)")
private String brand;

@Column(nullable = false)
private Integer productionYear;

@Column(nullable = false)
private Float engineCapacity;

@Column(nullable = false)
private Float power;

@Column(nullable = false)
private Integer distance;

@ManyToOne
@JoinColumn(name = "fkIdType")
private CarType carType;

@ManyToOne
@JoinColumn(name = "fkIdColor")
private Color color;
... }

这是DTO

public class CarDto {

private Long id;

private String brand;

private Integer productionYear;

private Float engineCapacity;

private Float power;

private Integer distance;

private CarTypes carType;

private ColorTypes color;
... }

CarTypesColorTypes是枚举,它们在数据库中分配了与其主键对应的编号。例如CarTypes是:

REGULAR_TWO_DOOR(1),
REGULAR_FOUR_DOOR(2),
STATION_WAGON(3),
MINIVAN(4),
SPORT(5),
LUXURY(6);

这是我设法编写的映射器。如何根据CarType主键为carEntity分配适当的CarType(该实体)?

public class CarMapper {

...
public static Car carDtoToCar(CarDto carDto, Car carEntity) {

    if(carEntity == null) {
        carEntity = new Car();
    }

    carEntity.setBrand(carDto.getBrand());
    carEntity.setProductionYear(carDto.getProductionYear());
    carEntity.setEngineCapacity(carDto.getEngineCapacity());
    carEntity.setPower(carDto.getPower());
    carEntity.setDistance(carDto.getDistance());

    Long carTypeId = Long.valueOf(carDto.getCarType().getNumber());
    Long carColorId = Long.valueOf(carDto.getColor().getNumber());

    /* ? */

    return carEntity;
}
}

CarType实体:

@Entity
@Table(name = "t_car_type")
public class CarType extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdType")
private Long id;

@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition="VARCHAR(45)")
private CarTypes type;
... }

1 个答案:

答案 0 :(得分:0)

根据Cartype ID获取Cartype实体。例如:

CarType carType = em.find(CarType.class, carTypeId);

然后在CarEntity中将此carType设置为

carEntity.setCarType(carType);

em - EntityManager