Create a bidirectional ManyToOne relation
Hi I try to create a ManyToOne relation but get stucked.
I have a BILL and a Booking Class
The realation is : A Bill can ha开发者_如何学JAVAve many Bookings. (1:m) The Bill Class should manage the relationship A Booking belong only to one Bill. (1:1 A Booking can't exist without a Bill )
If I delete the Bill, all Bookings that belongs to the Bill should be deleted. If I remove a Booking from the Bill, only this Booking should be deleted. If I delete a Booking, this Booking should be removed from the Bill.
So far i have this model :
Bill Class
@Entity
public class Bill extends Model{
@OneToMany(cascade={CascadeType.ALL})
public List<Booking> bookings;
public void setBookings(List<Booking> bookings)
{
for (Booking booking : bookings)
{
booking.bill = this;
}
}
}
Booking Class
@Entity
public class Booking extends Model{
@ManyToOne(optional=false )
@Required(message="Bill needed")
public Bill bill;
public void setBill(Bill bill){
this.bill=bill;
bill.bookings.add(this);
}
}
If I delete the Bill
, all Bookings belong to the Bill
deleted as well.
But I can't delete a single Booking
, either from the Bill
Side or the Booking
side.
What do I miss ?
Your case is the standard parent child case. You need to declare the following:
@Entity
public class Bill extends Model {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval=true, mappedBy="bill")
public List<Booking> bookings = new ArrayList<Booking>();
}
@Entity
public class Booking extends Model {
@ManyToOne public Bill bill;
}
This code contains all necessary declarations. The orphanRemoval ensures that whenever you delete a Booking from Bill (i.e., when that Booking becomes orphaned) it will be deleted from the database. If you delete the Bill, then all its BookingS are deleted as well (via the CascadeType.ALL annotation).
With the above declarations, you can set Bookings by
for(Booking booking : bookings) {
bill.bookings.add(booking);
booking.bill = bill;
}
(you don't need to code setBookings() yourself) but you must make sure that you do the change on both sides.
For removal, if you set a Booking's bill to null and remove the booking from the Bill's bookings:
booking.bill = null;
bill.bookings.remove(booking);
should do it.
If you call
booking.delete();
then also its bookings should be deleted.
Really quite standard....
精彩评论