Hibernate查詢,無資料正常,有資料出現java.lang.NullPointerException 異常
現象:
在使用struts+Spring+Hibernate時,執行多對一查詢時,出現異常!程式碼如下:
Hibernate影射檔案:
SGroup.hbm.xml
<hibernate-mapping>
<class name="com.news.Hibernate.SGroup" table="S_GROUP" schema="WHY">
<id name="groupid" type="java.lang.Integer">
<column name="GROUPID" precision="22" scale="0" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="20" />
</property>
<property name="remark" type="java.lang.String">
<column name="REMARK" length="500" />
</property>
<property name="status" type="java.lang.Integer">
<column name="STATUS" precision="22" scale="0" not-null="true" />
</property>
<set name="SGroupPrvs" inverse="true" cascade="all" lazy="true">
<key>
<column name="GROUPID" precision="22" scale="0"/>
</key>
<one-to-many class="com.news.Hibernate.SGroupPrv"/>
</set>
</class>
</hibernate-mapping>
SGroupPrv.hbm.xml
<hibernate-mapping>
<class name="com.news.Hibernate.SGroupPrv" table="S_GROUP_PRV" schema="WHY" lazy="true">
<composite-id>
<key-many-to-one name="SGroup" class="com.news.Hibernate.SGroup">
<column name="GROUPID" precision="22" scale="0"/>
</key-many-to-one>
<key-many-to-one name="SPrivilege" class="com.news.Hibernate.SPrivilege">
<column name="PRIVILEGE" precision="22" scale="0" />
</key-many-to-one>
</composite-id>
</class>
</hibernate-mapping>
java檔案:
else if(action!=null && action.equals("del")){
String groupid=request.getParameter("groupid");
System.out.print("組名id:"+groupid);
SGroup groups=groupManager.getSGroup(groupid);
groups.setGroupid(Integer.parseInt(groupid));
System.out.println("groupid:"+groups.getGroupid());
System.out.println("groupname:"+groups.getName());
System.out.print("是否例項化:"+Hibernate.isInitialized(groups));
if(!Hibernate.isInitialized(groups))
Hibernate.initialize(groups);
Set<SGroupPrv> set=groups.getSGroupPrvs();
System.out.print("是否例項化:"+Hibernate.isInitialized(set));
if(!Hibernate.isInitialized(set))
Hibernate.initialize(set);
System.out.print("是否例項化:"+Hibernate.isInitialized(set));
System.out.println(set.size());
}
如果資料庫中沒有記錄,則一切正常;如果資料庫中有記錄,則出現java.lang.NullPointerException 異常。
解決方式:
經在網上搜索後,終於找到解決的方法,現在與大家一起分享!
1、升級cglib_2.1.3.jar至cglib_2.2.jar;
2. 或者
更改載入方式為立即載入!即在多對一的影射中增加: lazy="false"
SGroupPrv.hbm.xml 採用的複合主鍵,所以不好修改
例如: *.hbm.xml:
<many-to-one name="SGroup"
class="com.news.Hibernate.SGroup" fetch="select" lazy="false" insert="false" update="false">
<column name="GROUPID" />
</many-to-one>