Krystian
Krystian

Reputation: 2290

Should Hibernate/JPA OneToMany be updated on both sides?

I have defined entities relation in Hibernate ORM with following code:

@Entity
public class Treatment {
    @OneToMany(fetch = FetchType.EAGER, mappedBy="treatment")
    private List<Consultation> consultations;
    ...
}

@Entity
public class Consultation {
    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "treatment_id")
    private Treatment treatment;
    ...
}

My question is, how should I update Treatment/Consultation when I want to make relation? Is it enough to update it on one side:

treatment.getConsultations().add(newCon);

Or should I update it on both sides?

treatment.getConsultations().add(newCon);
newCon.setTreatment(treatment);

How it looks in case of delete?

Upvotes: 4

Views: 1557

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

Well, using the mappedBy you tell Hibernate that the relationship is maintained by the other side, a filed called treatment in Consultation class. So first you have to get the consultation instance, then set the treatment, and finally persist the consultation instance. It will update all the references in the DB as integrity constraints (Primary Key/ Foreign Key pairs). So here the consultation table will have a treatmentId foreign key column pointing to the ID column (primary key) of the Treatment table.

an example code is,

Consultation consultation = new Consultation();
// This maintains the relationship.
consultation.setTreatment(treatment);
someDaoRepository.save(consultation);

Hope this helps, Happy Coding !

Upvotes: 1

Related Questions