Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/JPA, save a new entity while only setting id on @OneToOne association

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.

like image 732
mjs Avatar asked Nov 30 '25 04:11

mjs


1 Answers

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)
like image 171
mjs Avatar answered Dec 01 '25 16:12

mjs