我如何让Hibernate保存“父”实体,例如如果我有CarDescription是通过CarDescriptionDTO来自客户端的。

如果我现在想保存例如

Session session = HibernateSession.openSession();
session.beginTransaction();

CarDescription carDescription = ConvertDTO.convertCarDescription(carDescriptionDto);

session.save(carDescription);


如果此时Car没有设置carDescription,如何确保创建新的Car条目?还是我不想Hibernate为我做这件事?

汽车.java

@Entity
@Table(name = "car")
public class Car extends AbstractTimestampEntity implements Serializable {
    private static final long serialVersionUID = -5041816842632017838L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    // ..
}


如何确保这也会创建一个Car条目?

CarDescription.java

@Entity
@Table(name = "car_description")
public class CarDescription extends AbstractTimestampEntity implements Serializable {
    private static final long serialVersionUID = 2840651722666001938L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @NotNull
    @ManyToOne
    private Car car;

    // ..
}

最佳答案

有两种方法可以实现此目的。

1)您可以在Car的字段初始化程序中创建CarDescription

@NotNull
@ManyToOne(cascade = CascadeType.PERSIST)
private Car car = new Car();


您还定义了CascadeType.PERSIST,以便将car及其CarDescription保留在一起。这样,CarDescription默认情况下始终会有一辆空车。

2)您可以显式创建并保存car

Session session = HibernateSession.openSession();
session.beginTransaction();

CarDescription carDescription = ConvertDTO.convertCarDescription(carDescriptionDto);

Car car = new Car();
carDescription.setCar(car);

session.save(car);
session.save(carDescription);

关于java - 保存“子”实体时如何保持“父”实体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31267214/

10-09 02:55