开发者

Hibernate, instrumentation and delete cascade order

I have a complex object graph with JPA connected entities. When I delete the parent the deletions cascade correctly to the children.

Then I instrument the parent class (as to not load eagerly one-to-one relationships) and upon deletion I get referential integrity violation exceptions. Looking at the queries hibernate is开发者_StackOverflow中文版sues upon flush, I can see that hibernate indeed tries to delete records in a wrong order, thus the db complains for referential integrity and an exception is thrown.

Why this only manifests when the entities are instrumented? Is there a way to alter the delete cascade order?


I don't have an answer to your question but... why are you messing with "instrumentation" to make your one-to-one association lazy-loaded? I have tested the following for a one-to-one association between a class Foo and its FooDetail :

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
public FooDetail getFooDetail() {
    return detail;
}

And lazy-loading just works. This is the statement performed when retrieving a Foo instance:

Hibernate: select foo0_.id as id45_0_, foo0_.detail_id as detail3_45_0_, foo0_.shortName as shortName45_0_ from Foo foo0_ where foo0_.id=?

And, later, when calling the getter, the FooDetail is fetched:

Hibernate: select foodetail0_.id as id46_0_, foodetail0_.fullName as fullName46_0_ from FooDetail foodetail0_ where foodetail0_.id=?

And deleting a given Foo instance also works fine, the statements are executed in the right order:

Hibernate: delete from Foo where id=?
Hibernate: delete from FooDetail where id=?

Below, the DDL generated by Hibernate for the corresponding tables for reference:

create table Foo (id bigint not null, shortName varchar(255), detail_id bigint, primary key (id))
create table FooDetail (id bigint not null, fullName varchar(255), primary key (id))
alter table Foo add constraint FK212C3F68B31178 foreign key (detail_id) references FooDetail

Tested with Hibernate Annotations 3.4.0.GA.

Update: If this is not what you're looking for, then use a one-to-many association, there are limitations with a one-to-one association (and please clarify your question, readers can't guess what you don't write).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜