0

I have an entity of type A with a referenced member entity of type B. I want to insert a relationship between an instance of A to an existing instance of B without having to fetch B.

Is there a way to do it simply by ID? Something like:

B mockB = new B();

mockB.id = "id_persisted_b";

instanceA.setB(mockB);

Thanks.

Vlad Z.
  • 3,401
  • 3
  • 32
  • 60

3 Answers3

1

If you are using JPA you can use EntityManager.getReference() to obatin a proxy of the object without fetching all the fields, e.g.:

B mockB = entityManager.getReference(B.class, "id_persisted_b");
instanceA.setB(mockB);
David Levesque
  • 22,181
  • 8
  • 67
  • 82
0

If you use Fetch type LAZY hibernate will not load the object, it will load only a reference to it when you need. Is like having just the PrimaryKey of the element. It does that automatically.

lauksas
  • 533
  • 7
  • 14
0

Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class.

Lazy = true (means not to load child). By default the lazy loading of the child objects is true.

Shamse Alam
  • 1,285
  • 10
  • 21