org.hibernate.exception.MappingException或ConstraintViolation

时间:2013-02-07 06:41:47

标签: java hibernate

我正在使用hibernate 4.1.9。我有用户,用户有一个帐户列表,而帐户有交易列表。这是我的hbm.xml

<?xml version="1.0"?>

<class name="User" table="users">
    <id name="userId" column="userid">
        <generator class="increment"/>
    </id>
    <property name="username" column="username" not-null="true"/>
    <property name="password" column="password" not-null="true"/>
    <property name="registerDate" type="timestamp" column="register_date"/>
    <list name="accounts" table="accounts" inverse="true" cascade="all">
        <key column="userid" not-null="true"/>
        <index column="accountid"/>
        <one-to-many class="com.joe.data.Account"/>
    </list>
</class>
<class name="Account" table="accounts">
    <id name="accountId" column="accountid">
        <generator class="increment"/>
    </id>
    <property name="balance" type="big_decimal" column="balance"/>
    <property name="lastModified" type="timestamp" column="last_modified"/>
    <list name="txns" table="transactions" inverse="true" cascade="all">
        <key column="accountId" not-null="true"/>
        <index column="transactionId"/>
        <one-to-many class="com.joe.data.Transaction"/>
    </list>
    <many-to-one name="userId" class="User" column="userid" not-null="true" 
         unique="true" cascade="all"/> 
    <many-to-one name="accountType" class="AccountType" column="account_type" 
        not-null="true" cascade="all" unique="true" />
</class>
<class name="Transaction" table="transactions">
    <id name="transactionId" column="transactionid">
        <generator class="increment"/>
    </id>
    <property name="description" column="description"/>
    <property name="amount" type="big_decimal" column="amount"/>
    <property name="dateAdded" column="date_added"/>
    <property name="reoccuring" type="numeric_boolean" column="reoccuring"/>
    <many-to-one name="category" class="Category" column="category" 
        not-null="true" cascade="all" unique="true" />
</class>

<class name="Category" table="categories">
    <id name="categoryId" column="categoryid"/>
    <property name="categoryName" column="categoryname" not-null="true"/>
</class>
<class name="AccountType" table="account_types">
    <id name="accountType" column="account_type"/>
    <property name="accountName" column="name"/>
</class>

如果我在帐户列表中留下inverse =“true”(在User中),我会得到ConstraintViolationException,因为userid没有被放入insert查询中。如果我从account列表中取反向=“true”,我得到org.hibernate.MappingException:实体映射中的重复列:com.joe.data.Account列:accountid(应该用insert =“false”映射)更新= “假”)

为了阐明小写名称是数据库列的名称,camel case是类变量名。我知道Transaction类还没有正常工作,但如果我可以插入Accounts,我可以做同样的事情来插入Transactions。

编辑:我在Account类上添加了多对一,现在我又遇到另一个异常,其中hibernate抱怨在com.joe.data.Account <中错过了userId的getter / p>

1 个答案:

答案 0 :(得分:0)

为了获得inverse =“true”工作,您需要为Account中的User和Transaction类和映射中的Account定义多对一。