告诉 Hibernate 的 hbm2ddl 为 @Enumerated 注解字段添加 MySQL 枚举列
我正在使用 hbm2ddl 和类似于以下的 Java 代码创建一个数据库表:
@Entity
public class Filter {
public enum Type {
TypeA, TypeB;
}
@Enumerated(EnumType.STRING)
private Type type;
}
它工作正常,但是对于“类型”,创建了一个 VARCHAR 列,即 DDL 代码如下所示:
CREATE TABLE IF NOT EXISTS `filter` (`type` varchar(255) DEFAULT NULL)
但我想要的是
CREATE TABLE IF NOT EXISTS `filter` (`type` enum('TypeA','TypeB') NOT NULL)
:这可以在 Hibernate 中声明吗?最好使用注释?
或者有没有办法扩展 SchemaUpdate 并覆盖以我喜欢的方式呈现枚举字段的更改脚本部分的方法?
背景:项目的 PHP 部分使用相同的数据库,我想防止插入无效值。
I'm creating a DB table using hbm2ddl with Java code similar to the following:
@Entity
public class Filter {
public enum Type {
TypeA, TypeB;
}
@Enumerated(EnumType.STRING)
private Type type;
}
It works fine, but for "type" a VARCHAR column is created, i.e. the DDL code looks like this:
CREATE TABLE IF NOT EXISTS `filter` (`type` varchar(255) DEFAULT NULL)
But what I want to have is this:
CREATE TABLE IF NOT EXISTS `filter` (`type` enum('TypeA','TypeB') NOT NULL)
Is this possible to declare in Hibernate, preferred with annotations?
Or is there a way to extend SchemaUpdate and overwrite the method that renders the alter script part for enumerated field the way I like it?
Background: The same database is used in a PHP part of the project and I want to prevent that invalid values are inserted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管似乎没有办法 100% 自动处理 MySQL 枚举,正如 Lucas 在他的回答中指出的那样,但实际上有一种简单的方法可以解决它。您可以在
@Column
注释上使用columnDefinition
属性,该属性似乎是专门为生成自定义 DDL 代码而设计的。请参阅描述该属性的文档摘录:
NOT NULL
限制非常标准,并且由另一个属性nullable
支持。因此,您的属性定义将如下所示:
Although it seems there is no way to handle MySQL enums 100% automatically, as pointed out by Lucas on his answer, there is actually a simple way to contour it. You may use
columnDefinition
attribute on@Column
annotation, which seems to be specifically designed to generate custom DDL code.See the documentation excerpt describing the attribute:
The
NOT NULL
restriction is quite standard, and is supported by another attributenullable
.Thus, your property definition would look like this:
我相信这会很复杂,因为定义 java 处理的 sql 类型的 java.sql.Types 没有枚举类型(因为它不是根据 SQL-92 的标准化类型)。
如果是这种情况,您可以创建一个 hibernate 自定义 UserType 来扩展 EnumType 并相应地设置 sqlType,但由于 java.sql.Types 不处理它,我不知道如何使用本机 sql枚举。
此致!
I believe that's going to be complicated, since the java.sql.Types, which define the sql types treated by java, does not have enum type (since it's not a standardized type according to SQL-92).
If that was the case you could create a hibernate custom UserType extending the EnumType and setting the sqlType accordingly, but since java.sql.Types doesn't handle it I don't see how to use native sql enum.
best regards!