I have three classes (House, Room, Address) which are persistent (Mapped with JPA/Hibernate)
@Entity
@Table(name = "HOUSE")
@AttributeOverrides({@AttributeOverride(name = "house_id", column = @Column(name = "house_id"))})
public class House{
@Basic
private String key;
@OneToMany(mappedBy = "house", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<Room> rooms;
@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
@JoinColumn(name = "add_id")
private Address address;
}
public static void main(String args){
String key="key1";
Room room1=...
Room room2=...
List<Room> rooms=//add the two rooms
.
.
House house= new House(key, rooms, address);
// Here is my question.
// Now I call the save method on the persistent class
house.save();
}
1) Are Address and Room objects going to be persisted automatically or should I have to call save method on each of them (room1.save(), room2.save(), address.save()) before calling house.save()? How about when I delete the house obj?
2) The class “house” is the top of the hierarchy. I understood that if we call the save on the owning entity, it will persist the room and address as well. How about the reverse? If I edited the room, how do I make sure that the “house” knows about it?
not the way you have it set up. you need to mark one of your members in each entity as id with annotation
@Id. Then you need to map how your composed entities relate to each other. This is done with different annotations, such as@OneToManyand@ManyToOne.Finally, if you want to be able to persist composed entities by just calling hibernateSession.save with the owning entity in the relationship, all those entities it owns must be marked with cascade save, so that the persisting is cascaded down the ownership tree.