【发布时间】:2011-06-03 04:16:23
【问题描述】:
我有文件夹的父/子关系,如下所示:
一个文件夹可以有 0-1 个父文件夹。 一个文件夹可以有 0-n 个子文件夹(子文件夹)。
使用 Hibernate,我在这些文件夹上调用 session.update(folder)。
当这样的文件夹没有子文件夹时,一切正常。
但是当一个文件夹有子文件夹时,session.update(folder) 将使子文件夹瞬态(子文件夹的 id 从 4 变为 0!)。
怎么可能?
这是我的映射文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="test.Folder" table="FOLDERS">
<id name="id" type="long" access="field">
<column name="FOLDER_ID" />
<generator class="native" />
</id>
<set name="childFolders" table="FOLDERS" lazy="false" inverse="true" cascade="none">
<key column="PARENT_FOLDER_ID" not-null="false"></key>
<one-to-many class="test.Folder" />
</set>
<many-to-one name="parentFolder" column="PARENT_FOLDER_ID" />
<property name="name" column="FOLDER_NAME" />
<property name="rootFolder" column="IS_ROOT_FOLDER" type="boolean" not-null="true" />
<property name="path" column="FOLDER_PATH" />
<property name="type" column="FOLDER_TYPE" />
<property name="fullPath" column="FULL_PATH" unique="true" not-null="true" />
</class>
</hibernate-mapping>
更新:这是我用来更新文件夹的 Java 代码:
public class DatabaseController{
private SessionFactory sessionFactory = null;
public void updateFolder(Folder folder){
Session session = null;
Transaction transaction = null;
try {
session = getSession();
transaction = session.beginTransaction();
session.update(folder);
transaction.commit();
} catch (Exception e) {
rollback(transaction);
closeSession();
} finally {
closeSession();
}
}
/*
* Returns the Hibernate session
*/
private Session getSession() {
if (_session == null) {
_session = getSessionFactory().getCurrentSession();
}
if (_session.isOpen() == false) {
_session = getSessionFactory().openSession();
}
return _session;
}
/**
* Returns the session factory
*
* @return The session factory
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}
【问题讨论】:
-
请添加您用来更新实体的java代码。