Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java tools & IDE's > Hibernate on delete set null


Автор: LSD 15.9.2007, 12:28
Никак не разберусь, как в Hibernate реализовать поведение аналогичное БД - on delete set null. Т.е. чтобы при удалении объекта, у его дочерних объектов ссылка на родителя обнулялась. Пока получается только удалять их вместе с родителем.

Автор: mindflyer 15.9.2007, 23:25
Тоже не нашёл способа реализовать on delete set null.  И, точно не помню, но вроде именно об этом говорил коллега, что мол в инете на форумах по хиберу писали, что такой возможности вовсе нет.

Автор: Aoli 15.9.2007, 23:49
По-моему, это все-таки возможно было.
Исходя из этого дока:
Цитата

You can map entity associations in metadata with the following attributes:
■ cascade="none", the default, tells Hibernate to ignore the association.
■ cascade="save-update" tells Hibernate to navigate the association when the
transaction is committed and when an object is passed to save() or
update() and save newly instantiated transient instances and persist changes to
detached instances.
■ cascade="delete" tells Hibernate to navigate the association and delete persistent
instances when an object is passed to delete().
■ cascade="all" means to cascade both save-update and delete, as well as
calls to evict and lock.
■ cascade="all-delete-orphan" means the same as cascade="all" but, in addition,
Hibernate deletes any persistent entity instance that has been removed
(dereferenced) from the association (for example, from a collection).
■ cascade="delete-orphan" Hibernate will delete any persistent entity
instance that has been removed (dereferenced) from the association (for
example, from a collection)

если поставить save-update, то мы получим on delete set null.

Автор: LSD 16.9.2007, 13:57
Цитата(Aoli @  16.9.2007,  00:49 Найти цитируемый пост)
если поставить save-update, то мы получим on delete set null

Не получим, уже пробовал. Просто будет ошибка БД при удалении.

Автор: Aoli 16.9.2007, 16:11
А на другом форуме я нашел, что у человека обратная проблема:
Он использует all-delete-orphan и у него:
When I delete the project with a simple session.delete...the row is deleted in the table "project" but the row stays in table "subscription". Only the column entry "project" is set to null.
Цитата

I use Hibernate and I am not able to do cascade delete.

After I create a project I have:

select * from project;
uid | name | shortdescription
-----+------+-----------------
1 | nc | NC Web application
(1 row)

After I subscribe to the project I have:

select * from subscription;
uid | account | project | role
-----+---------+---------+------
1 | 1 | 1 | 1
(1 row)



When I delete the project with a simple session.delete

try {
session.delete(project);
session.flush();
} catch (HibernateException e) {...

the row is deleted in the table "project"
but the row stays in table "subscription". Only the column entry "project" is set to null.

select * from subscription;
uid | account | project | role
-----+---------+---------+------
1 | 1 | | 1
(1 row)

I want the row to be deleted, how do I do that?






My two tables one for Projects and one for Subscriptions


<hibernate-mapping>

<class name="org.cobra.persistence.Project" table="project">

<id name="id" column="uid" type="long">
<generator class="increment"/>
</id>

<property name="name">
<column name="name" sql-type="char(32)" not-null="true"/>
</property>

<property name="shortDescription">
<column name="shortDescription" sql-type="char(256)" not-null="true"/>
</property>

<set name="subscriptions" table="subscription" cascade="all-delete-orphan">
<key column="project"/>
<one-to-many class="org.cobra.persistence.Subscription"/>
</set>

<set name="subscriptionsRequested" table="subscriptionRequest" cascade="all-delete-orphan">
<key column="project"/>
<one-to-many class="org.cobra.persistence.SubscriptionRequest"/>
</set>

</class>

</hibernate-mapping>


<hibernate-mapping>

<class name="org.cobra.persistence.Subscription" table="subscription">

<id name="id" column="uid" type="long">
<generator class="increment"/>
</id>

<many-to-one name="account" column="account" cascade="all" class="org.cobra.persistence.Account" />

<many-to-one name="project" column="project" cascade="all" class="org.cobra.persistence.Project" />

<many-to-one name="role" column="role" cascade="all" class="org.cobra.persistence.Role" />

</class>

</hibernate-mapping>

Автор: LSD 16.9.2007, 21:24
В понедельник попробую повторить эксперимент.

Автор: LSD 17.9.2007, 23:01
Не сработало, все равно удаляет. Даже если на уровне базы сделать on delete set null.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)