主键类的关键部分代码如下:
public class TUserPK implements Serializable
{
private String firstname;
private String lastname;//这两个字段是表中影射过来的双主键
……//构造函数中初始化这两个主键。
……//两个字段的get,set方法
/**
*重写的equal方法
**/
public boolean equal(Object o)
{
if(this==o)return true;
if(!(o instanceof TUserPK))return false;
final TUserPK pk=(TUserPK) o;
if(!this.lastname.equals(pk.getLastname()))return false;
if(!this.firstname.equals(pk.firstname))return false;
return true;
}
/**
*重写的hashCode方法
**/
public int hashCode()
{
int result1;
int result2;
result1=(this.firstname==null?0:this.firstname.hashCode());
result2=(this.lastname==null?0:this.lastname.hashCode());
return result1+result2;
}
}
测试类关键代码
public class Test
{
……
TUserPK pk=new TUserPK( "AAA ", "BBB ");
TUser2 user=new TUser2();//TUser2类是POJO类
user=(TUser2) session.load(TUser2.class, pk);
System.out.println( "User age is => "+user.getAge());
……
}
用测试类运行时,抛如下异常
org.hibernate.PropertyAccessException: exception setting property value with CGLIB (set hibernate.cglib.use_reflection_optimizer=false for more info) setter of hibernate.table.TUser2.TUser2.setAge
at org.hibernate.tuple.PojoTuplizer.setPropertyValuesWithOptimizer(PojoTuplizer.java:203)
at org.hibernate.tuple.PojoTuplizer.setPropertyValues(PojoTuplizer.java:173)
at org.hibernate.persister.entity.BasicEntityPersister.setPropertyValues(BasicEntityPersister.java:2919)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:113)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:530)
at org.hibernate.loader.Loader.doQuery(Loader.java:436)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:218)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1345)
at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:116)
at org.hibernate.loader.entity.EntityLoader.load(EntityLoader.java:101)
at org.hibernate.persister.entity.BasicEntityPersister.load(BasicEntityPersister.java:2471)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:351)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:332)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:113)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:75)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:643)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:59)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)