我可以仅使用ID设置实体关系吗? [英] Can I set an entity relation with just the ID?
问题描述
我有一个JPA(Hibernate)实体:
@Entity类Transaction {
@ ManyToOne
私人房间;
当我创建一个新的 Transaction
,我知道它应该引用的 Room
的ID(但没有 Room
object)。我能以某种方式创建并保存 Transaction
这个信息,或者我确实需要:
房间= em.find(roomId,Room.class);
em.persist(new Transaction(room,...));
我遇到了类似的问题,但可能并非最佳做法。
现在由于映射取决于 roomId 创建构造函数房间(类型roomId )并在保存事务bean 之前设置该bean。所以需要从数据库中获取数据。 hibernate关心Id,它需要映射这些bean。
我已经使用这种方法来获取数据,我希望你不要当您更新交易时,会被更新。因此,将 insert,update映射的属性设置为false。
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, ...));
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.
这篇关于我可以仅使用ID设置实体关系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!