2

I have two entities,

  class A { @OneToOne B b; } 

  class B { ... lots of properties and associations ... } 

When I create new A() and then save, i'd like to only set the id of b.

So new A().setB(new B().setId(123)).

Then save that and have the database persist it.

I do not really need to or want to fetch the entire B first from the database, to populate an instance of A.

I remember this used to work, but when I am testing it is not.

I have tried Cascade All as well.

mmm
  • 18,431
  • 26
  • 99
  • 165

2 Answers2

2
B b = (B) hibernateSession.byId(B.class).getReference(b.getId());
a.setB(b);

hibernateSession.load(...) // can also be used as it does the same. 

The JPA equivalent is :

 entitymanager.getReference(B.class, id)
mmm
  • 18,431
  • 26
  • 99
  • 165
  • 1
    https://stackoverflow.com/questions/1607532/when-to-use-entitymanager-find-vs-entitymanager-getreference – aschoerk Aug 05 '17 at 10:01
-2

Below code should help.It will fetch B only when its accessed.

class A { @OneToOne(fetch = FetchType.LAZY) B b; }

zerocool
  • 1,927
  • 10
  • 14