Can I set an entity relation with just the ID?

烈酒焚心 提交于 2019-12-07 03:16:43

问题


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, ...));

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7847404/can-i-set-an-entity-relation-with-just-the-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!