Reputation: 396
Let assume that I have a relation Master Slave. In the database exists one row in the table Master with id=1. Why does this following code work:
Slave slave = new Slave();
slave.setId(1L);
Master master = new Master();
master.setId(1L);
slave.setMaster(master);
em.persist(slave);
So Master is detached entity and after commit refence between slave and master is created. Why? I thougt that in thikinf of case we have to read the Master row from the database by "find" function. Where can I read more about it?
Upvotes: 1
Views: 278
Reputation: 22672
Welcome to the dark land of Hibernate relations. First of all if you want to learn what is going on add to your hibernate.cfg.xml
<property name="show_sql">true</property>
Thanks to that you will see in console all SQL queries performed by Hibernate for you - that's the best way to figure out how Hibernate works in a given moment.
Back to your unexpected result. The important thing is who owns relationship. In your case I guess that in Slave table there is foreign key that points to Master table primary key (obviously you can use also join table - does not matter).
Hibernate, when creating relationship, cares only about that side, which owns relationship - in your case, it is enough to save information about new relation in Slave table. In fact Master does not need to know about relation, so it is not necessary to call save on that entity. That's why your code works.
Helpful read:
Upvotes: 1