Search code examples
javahibernateormhibernate-mappingcascade

How to persist "parent" entity when saving a "child" entity?


How can I let Hibernate save the "parent" entity e.g. if I have CarDescription that comes from a client via CarDescriptionDTO.

If I now want to save that e.g.

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

CarDescription carDescription = ConvertDTO.convertCarDescription(carDescriptionDto);

session.save(carDescription);

How can I make sure that a new Car entry gets created if carDescription does not have a Car set at this point? Or is this something I would not want Hibernate to do for me?

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

    // ..
}

how can I make sure that this also creates a Car entry?

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;

    // ..
}

Solution

  • There are two ways to achieve this.

    1) You can create the Car in the CarDescription's field initializer:

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

    You also define CascadeType.PERSIST so that the car is persisted together with its CarDescription. This way a CarDescription will always have an empty car by default.

    2) You can explicitly create and save the 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);