【问题标题】:DTO to entity mapping when entity has many to one relationship实体具有多对一关系时的 DTO 到实体映射
【发布时间】:2018-04-29 03:00:42
【问题描述】:

我正在尝试将业务对象映射到实体,但卡住了,不知道如何解决。

问题是当我尝试从 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;
... }

CarTypes 和ColorTypes 是在数据库中分配了与其主键相对应的编号的枚举。例如CarTypes 是:

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

这是我设法编写的映射器。如何根据CarType 主键将正确的CarType(即实体)分配给carEntity?

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;
... }

【问题讨论】:

    标签: java hibernate orm mapping


    【解决方案1】:
    • 根据 Cartype Id 获取 CarType 实体。例如:
      CarType carType = entityManager.find(CarType.class, carTypeId);

    • 然后将carType 中的CarEntity 设置为
      carEntity.setCarType(carType);

    【讨论】:

    • 有更短的方法来实现这一点吗?
    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 2019-01-14
    • 2018-09-13
    • 2018-01-13
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多