This is similar to How to cascade persist using JPA/EclipseLink
I have to entities like so. One is RoomEntity that has a one to many bi-directional relationship with ComputerEntity. eg. each room has 0..n computers.
@Entity
public class ComputerEntity implements Serializable {
@Id
@GeneratedValue(generator="computerSeq",strategy= GenerationType.SEQUENCE)
@SequenceGenerator(name="computerSeq",sequenceName="SEQUENCECOMPUTERID",allocationSize=1)
private long computerID;
@Column(name = "COMPUTERID")
public long getComputerID() {
return computerID;
}
public void setComputerID(long computerID) {
this.computerID = computerID;
}
private RoomEntity room;
@ManyToOne()
@JoinColumn(name = "ROOMID", referencedColumnName = "ROOMID")
public RoomEntity getRoom() {
return room;
}
public void setRoom(RoomEntity room) {
this.room = room;
}
} //ComputerEntity
@Entity
public class RoomEntity {
@Id
@GeneratedValue(generator="roomSeq",strategy= GenerationType.SEQUENCE)
@SequenceGenerator(name="roomSeq",sequenceName="SEQUENCEROOMID",allocationSize=1)
private long roomID;
@OneToMany(mappedBy = "room", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
private Set<ComputerEntity> computers;
@javax.persistence.Column(name = "ROOMID")
public long getRoomID() {
return roomID;
}
public void setRoomID(long roomID) {
this.roomID = roomID;
}
public Set<ComputerEntity> getComputers() {
return computers;
}
public void setComputers(Set<ComputerEntity> computers) {
for(ComputerEntity computer : computers) {
computer.setRoom(this);
}
this.computers = computers;
}
}//RoomEntity
When I try to persist an new room with a computer like so:
RoomEntity room = new RoomEntity();
room.setAdministrator("Fox Moulder");
room.setLocation("Area 51");
ComputerEntity computer1 = new ComputerEntity();
computer1.setDescription("Alienware area51 laptop");
Set<ComputerEntity> computers = new HashSet<ComputerEntity>();
computers.add(computer1);
room.setComputers(computers);
roomBean.createRoom(room);
roomBean is a Stateless EJB and roomBean.createRoom simply calls entityManager.persist(room). Since I have a CascadeType.PERSIST on the computers field of RoomEntity the ComptuerEntity is created. However, if I look at the room field of that ComputerEntity I see that room field is null. I would have assumed that Eclipselink would have automatically filled in the room since I have a bi-directional relationship. In order to have the room set in this way I had to add
for(ComputerEntity computer : computers) {
computer.setRoom(this);
}
to room.setComputers(...). Is this the correct approach or is there a way to get Eclipselink to automatically set this?
Thanks. -Noah