在 Hibernate JPA2 上使用唯一约束
如何在 hibernate POJO 上实现我的独特约束?假设数据库不包含任何内容。
我在 @Column()
注释中看到了唯一的属性,但我无法让它工作?
如果我想将此约束应用于多个列怎么办?
How can I implement my unique constraints on the hibernate POJO's? assuming the database doesn't contain any.
I have seen the unique attribute in @Column()
annotation but I couldn't get it to work?
What if I want to apply this constraint to more than one column?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在类中使用
@Table(uniqueConstraints = ...)
注解声明唯一约束You can declare unique constraints using the
@Table(uniqueConstraints = ...)
annotation in your class基本上,没有数据库支持就无法实现唯一约束。
@Column
的@UniqueConstraint
和unique
属性是模式生成工具生成相应约束的指令,它们本身不实现约束。您可以在插入新实体之前进行某种手动检查,但在这种情况下,您应该意识到并发事务可能出现的问题。
因此在数据库中应用约束是首选。
Bascially, you cannot implement unique constraint without database support.
@UniqueConstraint
andunique
attribute of@Column
are instructions for schema generation tool to generate the corresponsing constraints, they don't implement constraints itself.You can do some kind of manual checking before inserting new entities, but in this case you should be aware of possible problems with concurrent transactions.
Therefore applying constraints in the database is the preferred choice.
在 JPA2 中,您可以将唯一约束直接添加到字段:
恕我直言,将唯一约束直接分配给属性比在表的开头分配要好得多。
但是,如果您需要声明一个复合唯一键,那么在
@table
注释中声明它是您唯一的选择。In JPA2, you can add the Unique constraint directly to the field:
IMHO its much better to assign the unique constraint directly to the attributes than at the beggining of the table.
If you need to declare a composite unique key however, then declaring it in the
@table
annotation is your only option.