10

I have a many-to-one mapping on bookings. A booking must belong to a room. And a room can have several bookings.

If a room is deleted, I would like all the bookings on that room to be deleted as well. How would i go about doing this using hibernate annotations?

@Entity
public class Booking implements Serializable{

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Date startDate;
    private Date endDate;
    private Date createdDate;

    @ManyToOne
    @JoinColumn (name = "roomId")
    private Room room;
...
}
user829237
  • 1,719
  • 8
  • 37
  • 61

2 Answers2

13

In your Room entity you can have a

@OneToMany(cascade=CascadeType.REMOVE) 
private List<Booking> bookings;
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I do not have a list of bookings in my room entity. And if possible i would like to keep it that way. Is there any way to do this without introducing bookings into the room? – user829237 Oct 05 '11 at 13:04
  • No. But adding the collection costs you nothing (it will be lazy by default) – Bozho Oct 05 '11 at 13:12
4

Use

 @ManyToOne(cascade = CascadeType.REMOVE)
danny.lesnik
  • 18,479
  • 29
  • 135
  • 200
  • 1
    That will remove the room when some booking is removed, or it will surely try and might result in constraint violations if the room is associated with other bookings. – Shivan Dragon Oct 05 '11 at 12:57
  • This did not work... Still get the constraint error when trying to delete a room. – user829237 Oct 05 '11 at 13:03
  • @Andrei, We both are wrong here because many-to-one annotation doesn't have orphanRemoval property. :) but thank you. I didn't pay attention that it is Many-to-One I thought it was one-to-many :) I'll delete it later :) +1 on comment – danny.lesnik Oct 05 '11 at 13:07
  • 1
    Yep true, though it's worth mentioning that JPA's ManyToOne supports cascade remove, though the specs say that it's up to the implementator to decide what to do (meaning that it can chose to do nothing) – Shivan Dragon Oct 05 '11 at 14:20