Hibernate One-To-Many无法初始化集合

时间:2011-09-07 01:49:41

标签: java sql xml hibernate orm

我有两个数据库表,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 For 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());
}

1 个答案:

答案 0 :(得分:0)

我发现关系映射存在一些问题

用户表HBM:

 <set name="commentsMadeTo" inverse="true">
        <key column="XXXXXXXX"/>
        <one-to-many class="PageComment"/>
  </set>

HBM For PageComment:

<many-to-one name="userMadeTo" column="XXXXXXX" not-null="true" class="User" />

XXXXX 表示与“One”侧关联的“many”侧(即您的案例中的PageComment表)中的列名称。它在映射hbm中应该具有相同的值。

尝试将用户表的hbm更改为:

<set name="commentsMadeTo" inverse="true">
    <key column="Username"/>
    <one-to-many class="PageComment"/>
</set>