这类似于How to cascade persist using JPA/EclipseLink
我必须像这样的实体。一种是 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(room)。由于我在 RoomEntity 的计算机字段上有一个 CascadeType.PERSIST,因此创建了 ComptuerEntity。但是,如果我查看该 ComputerEntity 的房间字段,我会发现该房间字段为空。我会假设 Eclipselink 会自动填充房间,因为我有一个双向关系。为了以这种方式设置房间,我必须添加
for(ComputerEntity computer : computers) {
computer.setRoom(this);
}
到 room.setComputers(...)。这是正确的方法还是有办法让 Eclipselink 自动设置它?
谢谢。-诺亚