When I retrieve a Entity (row) with an intentionally unfetched many-to-one association and then try to update that Entity I get the famous transient instance error:
Error updating Object object references an unsaved transient instance - save the transient instance before flushing
But that "transient instance" was never fetched and so cannot even be transient
Code:
ProductFamily - java code
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>
Company - java code
public class Company
{
private String name;
private Set<ProductFamily> productFamilies = new HashSet<ProductFamily>(0);
//autogenerated getter & setter and constructors
}
Company - 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>
test method simple retrieve and change and update
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();
}
}