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