Can I set an entity relation with just the ID?
Asked Answered
C

2

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, ...));
Comintern answered 21/10, 2011 at 9:22 Comment(1)
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.Primeval
A
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.

Aborning answered 26/9, 2018 at 14:58 Comment(4)
Yes, since asking the question I've learned that this is indeed the correct wayComintern
Take a look at this to see an example.Peckham
Definitely what I was looking for! I think there are some questions that are thirsty for this answer.Fatality
According to baeldung.com/jpa-entity-manager-get-reference , this only avoids the round-trip to database for updates, not for delete or create operations.Churrigueresque
D
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.

Deliquescence answered 25/10, 2011 at 16:56 Comment(2)
I thought about that, but was worried that Hibernate would see the fake Room as not persisted yet. I'll try this.Comintern
@BartvanHeukelom: Did you try this? or got any issues?Deliquescence

© 2022 - 2024 — McMap. All rights reserved.