Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set an entity relation with just the ID?

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, ...));
like image 443
Bart van Heukelom Avatar asked Oct 21 '11 09:10

Bart van Heukelom


Video Answer


1 Answers

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.

like image 54
Sebastian Avatar answered Oct 02 '22 00:10

Sebastian