Here are parts of the definition of two class types,
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),
<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 reference in the employees. To check this I deliberately add an other Address reference to both employees. When both employees are persisted to the database, I see this that the foreign key in the employee is indeed the id of the container of the set where the employees are in. So that is OK. But the id of the Address reference in the employees are persisted to the second llevel cache, next to the id of the container of the set where the employees are in.
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); // deliberately other address employee2.setAddress(address3);
session.save(address); session.save(address3); session.save(employee); session.save(employee2);
tx.commit();
Then we do in a new session,
employee= (Employee) session.get(Employee.class, 1l); address=employee.getAddress(); employee= (Employee) session.get(Employee.class, 2l); address=employee.getAddress();
If we do not use Ehcache, address is (a proxy to) Address#12, so the container of the set where the employees belongs to, Address#12.. So this is OK. But if we do use Ehcache, address is aproxy to Address#34l, so the reference to the Address which we set deliberately in a employee instance with id 1 or 2.
So if we use a 2nd level cache, we get a different result.
When I debugged the Hibenate code, I found that the following method is empty, but this method should set employee.address,
BackrefPropertyAccessor$BackrefSetter.set(Object, Object, SessionFactoryImplementor){ }
|