开发者

Hibernate - retrieving all entities referenced by foreign keys for a specific entity

I´ve got a question similar to this one:

How to find all foreign keys?

I´d like to make Hibernate tell me whether an entity is referenced somewhere in the database by foreign keys. The background is: I want to implement a JIRA-l开发者_如何学运维ike behavior in my application: delete a user only, if there are no references to it and else refuse the delete operation.

I´m aware that there may be performance issues, but first of all, I´d only like to know whether this is doable or if you can think of a better way to achieve this.

One way to do this is to call delete and catch following exceptions, but I believe that there must be a better or more elegant way to do this?

Greetings, Chris


Hibernate has no concept or awareness of MySQL's foreign keys. Some options I can think of are:

  • Map both sides of the relationship in Hibernate (make sure that to mark them with inverse=true so that Hibernate doesn't try and use that side for updating the database). Then when you want to delete a user just make sure the .size() property of the various relationships is 0. I believe this would be the 'typical' Hibernate solution.
    • Cons - Once you have that side of the relationship in your objects it can be tempting to use it. Two-way associations can be tricky and need to be well understood.
  • Query each relationship checking to see if the user you are trying to delete is in their set. This is the least intrusive approach. You can use a count query to avoid having to send the entities into Java.
    • Cons - This is the most inefficient approach.
  • Use Native SQL If you were to try the delete and catch the exceptions you would already be relying on SQL (some databases don't have the concept of foreign keys). You're better off just issuing the query in native SQL at that point.
    • Cons - This adds a dependency in your program to SQL.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜