這類似於How to cascade persist using JPA/EclipseLink的EclipseLink/JPA2多對一雙向級聯堅持問題
我有實體,像這樣。一個是RoomEntity,它與ComputerEntity具有一對多的雙向關係。例如。每個房間有0..n臺電腦。
@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
當我試圖堅持一個新的房間用電腦就像這樣:
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是一個無狀態EJB和roomBean.createRoom簡單地調用entityManager.persist(室)。由於我在RoomEntity的計算機字段上有一個CascadeType.PERSIST,因此創建了ComptuerEntity。但是,如果我查看該ComputerEntity的房間字段,則會看到該房間字段爲空。因爲我有雙向關係,我會假設Eclipselink會自動填充房間。爲了有這樣的空間,我不得不添加
for(ComputerEntity computer : computers) {
computer.setRoom(this);
}
to room.setComputers(...)。這是正確的方法還是有辦法讓Eclipselink自動設置它?
謝謝。 - NOAH