Hibernate version: 3.2.4.sp1
Name and version of the database you are using: MySQL 5.0.27
Hi,
I'm trying to model a unidirectional many-to-one association on a join table (as per chapter 7.3.2 of the documentation):
Code:
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<join table="PersonAddress"
optional="true">
<key column="personId" unique="true"/>
<many-to-one name="address"
column="addressId"
not-null="true"/>
</join>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
</class>
Everything works fine if I create Person, Address and the connection between them in the same transaction:
Code:
Address address = new Address();
dao.saveAddress(address);
Person person = new Person();
person.setAddress(address);
dao.savePerson(person);
The save() methods use saveOrUpdate() to persist the objects.
The Address record is created, the Person record is created and one record is inserted to PersonAddress.
However, when I work with a Person (which doesn't currently have an Address) created in another session and try to associate it with a new or existing Address, saving the Person will not create the relation data:
Code:
// In another session ...
Person person = new Person();
// flush() etc
Address address = new Address();
dao.saveAddress(address);
person.setAddress(address);
dao.savePerson(person);
What's happening is this: The new Address is created in the DB, the Person record is updated, but instead of inserting a record into PersonAddress, Hibernate is submitting an Update to PersonAddress, with the Person's id in the where clause. Since no Address has been specified for this Person yet, there's nothing to update.
No error message is shown, it just fails silently.
This is a quite common use case, e.g. when using a GUI where the user can associate a Person with an existing Address. I guess I'm missing something fundamental here, which is probably easy to fix.
Thanks in advance!
Nils
[/code]