3
我有兩個數據庫表User,PageComment。使用Hibernate,我試圖通過在hbm XML文件中使用一對多關係,在User評論(對該用戶發表的評論)中存儲一組PageComment對象。休眠一對多不能初始化集合
問題是,我似乎能夠從User對象中檢索集合,但只要我嘗試訪問存儲在集合中的任何對象,或者甚至訪問集合中包含的方法類(即size()),JVM會拋出「org.hibernate.exception.GenericJDBCException:無法初始化集合」。我在這一個上虧本。
HBM對於用戶表:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user">
<id name="username" column="Username" type="string">
<generator class="assigned"></generator>
</id>
<property name="password" column="Password" type="string"></property>
<property name="firstname" column="Firstname" type="string"></property>
<property name="surname" column="Surname" type="string"></property>
<property name="email" column="Email" type="string"></property>
<property name="admin" column="Admin" type="integer"></property>
<set name="commentsMadeTo" inverse="true">
<key column="userMadeTo"/>
<one-to-many class="PageComment"/>
</set>
</class>
</hibernate-mapping>
HBM對於PageComment:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="PageComment" table="PageComment">
<composite-id>
<key-property name="userMadeBy" column="UserMadeBy" type="string" />
<key-property name="userMadeTo" column="UserMadeTo" type="string" />
<key-property name="time" column="Time" type="integer" />
<generator class="assigned"></generator>
</composite-id>
<property name="commentText" column="CommentText" type="string"></property>
<many-to-one name="userMadeTo" column="Username" not-null="true" class="User" />
</class>
</hibernate-mapping>
我試圖測試用此方法的映射:
Session session = sessionFactory.openSession();
User theUser = (User)session.createQuery("FROM User WHERE Username='Samat'").uniqueResult();
System.out.println("Trying to print out all comments made to 'Samat'");
Set<PageComment> theComments = theUser.getCommentsMadeTo();
for(PageComment p: theComments){
System.out.println(p.getAllData());
}
你可能需要到顯示完整的堆棧跟蹤,尤其是GenericJDBCException的根本原因。 –