如果你为某个class设置了proxy="...",那么hibernate会在运行时用CGLib生成一个
proxy="..."所指定的这个类的一个子类作为你的那个entity class的proxy。
比如说你为Cat指定proxy="Cat",hibernate会继承Cat,生成一个代理类,就叫CatProxy(我随便取的)吧
同样对DomesticCat,hibernate会继承DomesticCat,生成一个代理类,就叫DomesticCatProxy吧
Cat cat = (Cat) session.load(Cat.class, id); // instantiate a proxy (does not hit the db)
//cat的实际类型就是CatProxy,你可以调用cat.getClass().getName()和cat.getClass().getSuperClass().getName()就知道了
if ( cat.isDomesticCat() ) { // hit the db to initialize the proxy
DomesticCat dc = (DomesticCat) cat; // Error!
//从CatProxy转型到DomesticCat,显然不对
....
}
Secondly, it is possible to break proxy ==.
Cat cat = (Cat) session.load(Cat.class, id); // instantiate a Cat proxy
DomesticCat dc =
(DomesticCat) session.load(DomesticCat.class, id); // required new DomesticCat proxy!
System.out.println(cat==dc);
这一段也没明白 这里的break proxy == 是什么意思
//就是会打出false,cat和de的类型分别是CatProxy和DomesticCatProxy,怎么会相等呢?
However, the situation is not quite as bad as it looks. Even though we now have two references to different proxy objects, the underlying instance will still be the same object:
cat.setWeight(11.0); // hit the db to initialize the proxy
System.out.println( dc.getWeight() ); // 11.0
//这两个proxy的底层是同一个对象