Hibernate, Persistence and @OneToMany and @ManyToOne annotations problems

烈酒焚心 提交于 2019-12-22 09:22:03

问题


I have some problem with @OneToMany and @ManyToOne annotations.

I have two class Suite and SuiteVersion. A SuiteVersion is dependent of a suite. So i have implemented this in my code:

Class Suite :

@OneToMany(mappedBy = "suite")
@Cascade(CascadeType.DELETE_ORPHAN)
private List<SuiteVersion> listSuiteVersion = new ArrayList<SuiteVersion>();

Class SuiteVersion :

@ManyToOne()
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
private Suite suite;

But i have some problem when i delete a Suite whose have SuiteVersion associated. Hibernate don't delete SuiteVersion before Suite.I don't know why because i have mentioned this in my code :

@Cascade(CascadeType.DELETE_ORPHAN)

This the log i obtained when i delete suite :

Hibernate: delete from SUITE where ID_SUITE=? 13 août 2010 09:40:50 org.hibernate.util.JDBCExceptionReporter logExceptions ATTENTION: SQL Error: -8, SQLState: 23504 13 août 2010 09:40:50 org.hibernate.util.JDBCExceptionReporter logExceptions GRAVE: integrity constraint violation: foreign key no action; FK42895651EA304E6 table: SUITE_VERSION

Thank you in advance for your help.

Best Regards,

Florent,

P.S : Sorry for my english i'm french.


回答1:


But i have some problem when i delete a Suite whose have SuiteVersion associated. Hibernate don't delete SuiteVersion before Suite.

That's because you're NOT cascading the REMOVE operation from Suite to SuiteVersion. To obtain the desired result, you need something like this (assuming you're using JPA 1.0):

@OneToMany(mappedBy = "suite", cascade = javax.persistence.CascadeType.REMOVE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<SuiteVersion> listSuiteVersion = new ArrayList<SuiteVersion>();

I used fully qualified names to clearly show the Hibernate specific and the standard JPA annotations here.

The Hibernate specific CascadeType.DELETE_ORPHAN is something else, it is used to tell Hibernate to delete a specific SuiteVersion if you remove it from the collection (without it, the SuiteVersion record would be updated to remove the link to the parent Suite but would remain in the table, being thus an "orphan").

Note that if you are using JPA 2.0 (i.e. Hibernate 3.5+), there is now a standard way to deal with orphan records i.e. without using the Hibernate specific annotation. You can specify an orphanRemoval option in your OneToMany (and OneToOne) association. Like this:

@OneToMany(mappedBy = "suite", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<SuiteVersion> listSuiteVersion = new ArrayList<SuiteVersion>();

But this goes beyond this question as this is actually not what you're looking for.



来源:https://stackoverflow.com/questions/3474918/hibernate-persistence-and-onetomany-and-manytoone-annotations-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!