这类似于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自动设置它?
感谢。 -Noah
答案 0 :(得分:1)
JPA没有关系维护。 EJB 2.1表明,通用关系管理效率低下且过于繁琐。
我建议添加一个addComputer()方法,该方法会在新添加的ComputerEntity上设置RoomEntity