使用@Enumerated时检查约束? Spring Boot-JPA
如果我有以下实体和枚举:
public enum MyEnum {
VALUE_1,
VALUE_2
}
@Entity
public class MyEntity {
@Enumerated(EnumType.STRING)
private MyEnum myEnum;
}
有没有一种方法可以在数据库上创建约束,而不必在 SQL 中实际编写约束?
这就是我想避免的:
@Column(columnDefinition = "VARCHAR(60) CHECK (myEnum IN ('VALUE_1', 'VALUE_2')))
If I have the following entity and enum:
public enum MyEnum {
VALUE_1,
VALUE_2
}
@Entity
public class MyEntity {
@Enumerated(EnumType.STRING)
private MyEnum myEnum;
}
Is there a way to have a constraint created on the database without me having to actually write the constraint in SQL?
This is what i want to avoid:
@Column(columnDefinition = "VARCHAR(60) CHECK (myEnum IN ('VALUE_1', 'VALUE_2')))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
谈论
columnDefinition
属性来源
以及关于 JPA
[2]
从这些引用中,我认为:
使用
columnDefinition
属性是最佳实践,特别是因为 JPA 是您用来保存数据库的工具不,没有其他更好的方法来在数据库中创建约束
[2]: https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/undejbs003.htm#:~:text=%20Java%20Persistence%20API%20(JPA,standard%2C%20portable%20way%20that %20作品
Speaking about the
columnDefinition
attributesource
and about JPA
[2]
From these citings, I think:
using the
columnDefinition
attribute is the best practice especially since JPA is the tool you are using to persist your DBNo, there is no other way better way to create the constraints in the database
[2]: https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/undejbs003.htm#:~:text=The%20Java%20Persistence%20API%20(JPA,standard%2C%20portable%20way%20that%20works