可以只用ID设置实体关系吗?
我有一个 JPA (Hibernate) 实体:
@Entity class Transaction {
@ManyToOne
private Room room;
}
当我创建一个新的 Transaction
时,我知道它应该引用的 Room
的 ID(但没有 <代码>房间对象)。我可以仅使用此信息以某种方式创建并保留 Transaction
吗?或者我真的需要:
Room room = em.find(roomId, Room.class);
em.persist(new Transaction(room, ...));
I have a JPA (Hibernate) entity:
@Entity class Transaction {
@ManyToOne
private Room room;
}
When I create a new Transaction
, I know the ID of the Room
that it should refer to (but don't have a Room
object). Can I somehow create and persist a Transaction
with just this info, or do I really need to:
Room room = em.find(roomId, Room.class);
em.persist(new Transaction(room, ...));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 EntityManager.getReference() 来获取相关实体的代理,而无需访问数据库。该代理是延迟初始化的,仅当您查询实体 ID 以外的任何内容时才会初始化。
You can use
EntityManager.getReference()
to get a proxy of the related entity without accessing the database. This proxy is lazy-initialized and will be initialized only when you query anything other than the ID if the entity.我遇到了类似的问题,我找到了替代解决方案,但可能不是最佳实践。
现在,由于映射取决于 roomId,因此创建一个构造函数 Room(Type roomId) 并在保存事务 bean 之前设置该 bean。所以需要从DB中获取数据。 hibernate 关心映射 beans 所需的 Id。
我已经使用这种方法来获取数据,我希望您不希望在更新交易时更新房间。因此,将映射的插入、更新属性设置为 false。
I had a similar problem where I found an alternate solution but may be its not a best practice.
Now since the mapping is depending on the roomId create a constructor Room(Type roomId) and set that bean before you save Transaction bean. So need to get the data from the DB. What hibernate cares about the Id that it needs to map the beans.
I have used this approach to get the data and I hope you don't want the Room to get updated when you update Transaction. So set the insert,update properties of the mappings to false.