項(xiàng)目用的持久化層是hibernate 2.1.6.
前不久出現(xiàn)一個(gè)錯(cuò)誤,簡(jiǎn)單描述一下:

現(xiàn)有3個(gè)對(duì)象:Party,TParty和Individual,其中Individual是Party的子類,Party和TParty各自獨(dú)立,兩個(gè)對(duì)象都映射到表T_Party。

當(dāng)獨(dú)立執(zhí)行Individual person = (Individual)session.load(Individual.class, id)時(shí),系統(tǒng)正確,.
而在同一thread下(OpenSessionInView),先session.find("from TParty"),再Individual person = (Individual)session.load(Individual.class, id)系統(tǒng)報(bào)錯(cuò)ClassCastException,經(jīng)查此時(shí)系統(tǒng)返回的是TParty對(duì)象。

初步斷定是hibernate問題,參看hiberante 2.1.7沒有覺的有什么問題(因?yàn)樽约弘娔X本地有這個(gè)版本,事實(shí)證明這是個(gè)錯(cuò)誤)。折騰了一天,沒有發(fā)現(xiàn)問題所在,最后只好下載了hibernate2.1.6,立刻發(fā)現(xiàn)問題所在。
hibernate在load對(duì)象時(shí),會(huì)通過getEntity(key)查看是否加載過,而Key對(duì)象幾個(gè)主要方法如下:

private ?Key(Serializable?id,?Serializable?identifierSpace,?Class?clazz,? boolean ?batchLoadable)? {
????????
if ?(id == null )? throw ? new ?AssertionFailure( " null?identifier " );
????????
this .identifier = id;
????????
this .identifierSpace? = ?identifierSpace;
????????
this .clazz? = ?clazz;
????????
this .isBatchLoadable? = ?batchLoadable;
????}

????
????
/**
?????*?Construct?a?unique?identifier?for?an?entity?class?instance
?????
*/

????
public ?Key(Serializable?id,?ClassPersister?p)? {
????????
this (?id,?p.getIdentifierSpace(),?p.getMappedClass(),?p.isBatchLoadable()?);
????}


public ? boolean ?equals(Object?other)? {
????????Key?otherKey?
= ?(Key)?other;
????????
return ?otherKey.identifierSpace.equals( this .identifierSpace)? && ?otherKey.identifier.equals( this .identifier);
????}

????
????
public ? int ?hashCode()? {?
????????
int ?result? = ? 17 ;
????????result?
= ? 37 ? * ?result? + ?identifierSpace.hashCode();
????????result?
= ? 37 ? * ?result? + ?identifier.hashCode();

這個(gè)Key在hiberante幾個(gè)版本都一樣
但在ClassPersister在2.1.6和2.1.7卻有不同:
hibernate 2.1.7中在AbstractEntityPersister中

public ?Serializable?getIdentifierSpace()? {
????
return ?rootClassName;
}

但在hibernate 2.1.6 中的EntityPersister

? public ?Serializable?getIdentifierSpace()? {
??
return ?qualifiedTableName;
?}

問題就出在這里。趕緊把hibernate從2.1.6升級(jí)到2.1.8。