8

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, ...));
Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
  • I too have this requirement to avoid unnecessary database queries to fetch the child object purely for the purpose of setting it in a foreign key relationship. – Sridhar Sarnobat May 30 '18 at 00:36

2 Answers2

5

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.

Sebastian
  • 1,651
  • 1
  • 11
  • 12
  • Yes, since asking the question I've learned that this is indeed the correct way – Bart van Heukelom Oct 14 '18 at 17:34
  • Take a look at [this](https://stackoverflow.com/a/32542366/4071001) to see an example. – lcnicolau Jul 03 '19 at 13:37
  • Definitely what I was looking for! I think there are some questions that are thirsty for this answer. – greg93 Sep 29 '22 at 09:53
  • According to https://www.baeldung.com/jpa-entity-manager-get-reference , this only avoids the round-trip to database for updates, not for delete or create operations. – kistlers Dec 07 '22 at 08:22
0

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.

ManuPK
  • 11,623
  • 10
  • 57
  • 76