Hibernate:跨多个表的@UniqueConstraint?

发布于 2024-11-09 22:42:04 字数 679 浏览 5 评论 0原文

我有一个数据模型,其中许多实体从单个超类实体继承一些公共属性。我在超类上使用 InheritanceType.JOINED ,这会导致 Hibernate 为超类中定义的属性创建单个表,子类表仅包含子类添加的列(以便加载属性对于子类实例,在两个表之间执行联接)。这一切都工作正常。

然而,我想做的是指定一个唯一约束,其中包括子类表和超类表中的字段。例如,假设我的超类实体类似于:

Thing: {id, name}

...然后我有一些子类实体,例如:

Company: {address}  //inherits 'id' and 'name' from 'Thing'
Employee: {company} //inherits 'id' and 'name' from 'Thing'

...并且我想配置 Hibernate 以自动强制给定的 Company 不能有两个员工同名。 company 字段在 Employee 表中,但 name 字段在 Thing 表中,所以有有什么方法可以让 Hibernate 强制执行此约束,或者每当我添加新的 Employee 时是否需要以编程方式执行此操作?

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 the 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

捎一片雪花 2024-11-16 22:42:04

如果它在数据库中不可能,那么在 Hibernate 中也不可能。您无法使用 SQL 在多个表上创建一个约束,因此在 Hibernate 中也是如此。

您可以通过创建一个仅包含公司和员工 ID 的新实体并在这两个字段上设置唯一约束来解决此问题,但我建议以编程方式强制执行此操作。

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.

深空失忆 2024-11-16 22:42:04

您可以使用InheritanceType.JOINED,那么所有内容最终都会出现在一个巨大的表中,您可以编写您的约束。如前所述:您想要的在关系数据库中是不可能的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文