0

当我检索具有故意未提取的多对一关联的实体(行)然后尝试更新该实体时,我得到了著名的瞬态实例错误:

更新 Object 对象引用未保存的瞬态实例时出错 - 在刷新之前保存瞬态实例

但是那个“瞬态实例”从未被提取,因此甚至不能是瞬态的

代码:

ProductFamily - java 代码

public class ProductFamily
{
    private Integer id;
    private Company company;
    private String name;

    //autogenerated getter & setter and constructors
}

ProductFamily - hbm.xml

<hibernate-mapping>
    <class name="package.ProductFamily" table="product_family" catalog="db">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <many-to-one name="company" class="package.Company" fetch="select">
            <column name="company" not-null="true"/>
        </many-to-one>
        <property name="name" type="string">
            <column name="name" length="64" not-null="true"/>
        </property>
    </class>
</hibernate-mapping>

公司-java代码

public class Company
{
    private String name;
    private Set<ProductFamily> productFamilies = new HashSet<ProductFamily>(0);
    //autogenerated getter & setter and constructors
}

公司 - hbm.xml

<!-- same header as above -->
<hibernate-mapping>
    <class name="package.Company" table="company" catalog="db">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="64" not-null="true"/>
        </property>
        <set name="productFamilies" table="product_family" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="company" not-null="true"/>
            </key>
            <one-to-many class="package.ProductFamily" />
        </set>
    </class>
</hibernate-mapping>

测试方法简单的检索和更改和更新

public void test()
{
    final StatelessSession session = this.sessionFactory.openStatelessSession();

    //get
    final ProductFamily productFamily = (ProductFamily)session.get(ProductFamily.class, 1);

    //change primitive property
    productFamily.setName(productFamily.getName() + "x");

    //update
    final Transaction tr = session.beginTransaction();

    try
    {
        session.update(productFamily);
        tr.commit();
    }
    catch (HibernateException e)
    {
        logger.severe(e.getMessage() + "\n" + e.getStackTrace());
        try
        {
            if(tr != null
                && tr.isActive())
                tr.rollback();
        }
        catch (HibernateException eTr)
        {
            logger.severe(eTr.getMessage() + "\n" + eTr.getStackTrace());
        }
    }
    finally
    {
        session.close();
    }
}
4

2 回答 2

0

错误出现在我以前没有使用过的 StatelessSession 中。忘记提了。

于 2012-04-18T01:14:37.677 回答
0

我无法重现问题。根据您的代码重新创建项目。数据库 - MySQL,Hibernate 4.1.1。代码毫无例外地工作。

所以,这里是我的项目的链接。我决定将它与我使用的库一起打包(这样您就可以检查特定版本的库是否出现问题)。

build.xmlprint包含 3 个以预定义参数(create和)开头的目标test

于 2012-04-17T17:06:56.680 回答