我如何让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/