Hibernate: @UniqueConstraint Across Multiple Tables?
I have a data model in which a number of entities inherit some common attributes from a single superclass entity. I am using InheritanceType.JOINED
on the superclass, which causes Hibernate to create a single table for attributes defined in the superclass, with subclass tables containing only columns that are added by the subclass (so to load the attributes for a subclass instance, a join is performed between the two tables). That is all working fine.
What I'd like to do, however, is specify a unique constraint that includes fields in both the subclass and superclass tables. For instance, say that my superclass entity is something like:
Thing: {id, name}
...and then I have some subclass entities like:
Company: {address} //inherits 'id' and 'name' from 'Thing'
Employee: {company} //inherits 'id' and 'name' from 'Thing'
...and I want to configure Hibernate to automatically enforce that a given Company
cannot have two Employee
's with t开发者_StackOverflow中文版he same name. The company
field is in the Employee
table, but the name
field is in the Thing
table, so is there any way to get Hibernate to enforce this constraint, or do I need to do it programmatically whenever I add a new Employee
?
If it's not possible in the Database it won't be possible with Hibernate. You can't create one constraint on multiple tables with SQL so neither in Hibernate.
You could work around this by creating a new Entity holding only the company and employee id and setting a unique constraint on those 2 fields but I would recommend enforcing this programmatically.
You could not use InheritanceType.JOINED
, then everything ends up in a huge table, and you could write your constraint. As said before: What you want is just not possible in a relational DB.
精彩评论