Saturday, March 14, 2009

Same EntityKey for parent and child objects

This happens when modeling inheritance classes. If parent and child object which all extend same root class happens to use the same value for id, that's pretty fine since parent and child are different tables, but Hibernate will actually generate same entity key for them. That will lead to org.hibernate.WrongClassException.

After tracing into Hibernate, the reason looks to me is that Hibernate is using rootEntityName to generate hashcode for all subclasses. It will break if subclasses are using same id.

For example, Department (Dept) and Employee (Emp) class all extend from class Entity which has id attribute. When loading department and join fetching employees, if id in Dept table happens to have the same id in Emp table, that won't work. As of Hibernate 3.3.1 GA, in org.hibernate.engine.EntityKey:



private int generateHashCode() {
int result = 17;
result = 37 * result + rootEntityName.hashCode();
result = 37 * result + identifierType.getHashCode( identifier, entityMode, factory );
return result;
}



So the Dept and Emp are getting the same hashcode, and when loading Emp, Hibernate think it's already in cache, but that's Dept instance.

There is actually a ticket (not assigned yet) in Hibernate Jira: http://opensource.atlassian.com/projects/hibernate/browse/HHH-3445

It's easy to patch, but not sure whether it will break other parts in Hibernate.

No comments:

Post a Comment