Here are parts of two class types,
Code:
public class Address {
Set<Employee>employees=new HashSet<Employee>();
public class Employee {
private Address address;;
Employees works on the address, for example. The mapping to Hibernate of them is (partly),
Code:
<class name="Address">
<cache usage="read-write"/>
<set name="employees" inverse="false">
<cache usage="read-write"/>
<key column="address_" not-null="true"/>
<one-to-many class="Employee"/>
</set>
</class>
<class name="Employee" >
<cache usage="read-write"/>
<many-to-one name="address" column="address_" not-null="true" insert="false" update="false"/>
So we have a bidirectional one-to-many association. The persistence of the association is determined by the collection side , not by the Address references in the employees. To check this I deliberately add Address references to both employees. When both employees are persisted to the database, I see this is indeed the case. But the two Address references are persisted to the second llevel cache, and this is what I do not understand.
Code:
Employee employee=new Employee(1l,"Foo1",1.00);
Employee employee2=new Employee(2l,"Foo2",2.00);
Address address=new Address(12l,"foostreet", "12 foo", "FooCity12");
Address address3=new Address(34l,"foostreet", "34 foo", "FooCity34");
address.getEmployees().add(employee);
address.getEmployees().add(employee2);
employee.setAddress(address3);
employee2.setAddress(address3);
session.save(address);
session.save(address3);
session.save(employee);
session.save(employee2);
tx.commit();
Then in a new session,
Code:
employee= (Employee) session.get(Employee.class, 1l)l
address=employee.getAddress();
employee= (Employee) session.get(Employee.class, 2l);
address=employee.getAddress();
Without Ehcache address is (a proxy to) Address#12l, so the container of the set where the employees belongs to, Address#12l. But with Ehcache address is aproxy to Address#34l, so the reference to the Address which we set deliberately.
I don't know how this could ever work, because
Code:
BackrefPropertyAccessor$BackrefSetter.set(Object, Object, SessionFactoryImplementor){
}