JPA,使用 ManyToOne 外键存储实体

JPA, store an Entity with ManyToOne foreign keys

我已经成功创建了一个实体(以及相应的数据 table),如下所示:

@XmlRootElement
@Entity
@Table(name = "USERS_BOOK")
public class UsersBook {

@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =     "USERS_BOOK_SQ")
private long              id;

@ManyToOne(fetch = FetchType.EAGER, optional = true)
private Room            room;

@ManyToOne(fetch = FetchType.EAGER, optional = true)
private Building        building;

它为相应的实体(房间和建筑物)创建一个带有 2 个外键(room_id 和 building_id)的 table。

现在我想存储一个新的 UsersBook 链接到一个房间和一个建筑物,已经存储在我的数据库中。

我已经知道房间 table 和建筑物 table 中一行的主键 (ID)。

如何告诉 JPA 使用我已经拥有的 Room 和 Building 外键?

希望我说得够清楚了。

谢谢大家!

使用EntityManager.find()(在数据库中实际找到它们)或EntityManager.getReference()(获得一个统一化的代理,假设它们确实存在于数据库中):

Room room = em.getReference(Room.class, roomId);
Building building = em.getReference(Building.class, buildingId);
UsersBook book = new UsersBook();
book.setRoom(room);
book.setBuilding(building);
em.persist(book);