gpt4 book ai didi

java - Hibernate session.update(object) 方法使子对象 transient (在父/子关系中)

转载 作者:行者123 更新时间:2023-12-01 06:20:56 24 4
gpt4 key购买 nike

我有文件夹的父/子关系,如下所示:

一个文件夹可以有 0-1 个父文件夹。一个文件夹可以有0-n个子文件夹(子文件夹)。

使用 Hibernate,我对这些文件夹调用 session.update(folder)

当这样的文件夹没有子文件夹时,一切正常。

但是当文件夹有子文件夹时,session.update(folder) 将使子文件夹变为 transient (子文件夹的 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;
}
}

最佳答案

正确

您的集合定义中有cascade="none"

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#objectstate-transitive

您需要设置cascade="save-update"。

关于java - Hibernate session.update(object) 方法使子对象 transient (在父/子关系中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6176488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com