當我取回實體(行)與故意未抓取許多-to-one關聯,然後嘗試更新實體,我得到了著名瞬態的實例錯誤:休眠StatelessSession更新多對一不工作(瞬態實例)?
更新對象時出錯 對象引用一個未保存的瞬態的實例 - 沖洗
之前保存的瞬態的實例,但「短暫的實例」從來沒有取出,並因此甚至不能瞬時
代碼:
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();
}
}
請顯示您的代碼。關於故意取消關聯,修改實體和「更新」的部分。 – 2012-04-16 17:12:14
我添加了一個仍然產生相同錯誤的簡單示例。 – djmj 2012-04-16 22:28:24