以下 JPA 列定义默认在所有数据库(例如 h2、mysql、postgres)上生成“整数”数据类型,
@Column(name = "type", nullable = false)
@Type(type = "com.mycompany.hibernate.usertype.GenericEnumUserType", parameters = {
@Parameter(name = "enumClass", value = "com.mycompany.model.DegreeType"),
@Parameter(name = "identifierMethod", value = "toInt"),
@Parameter(name = "valueOfMethod", value = "fromInt") })
@NotNull
private DegreeType type;
我希望为此字段使用最小存储空间,因此更愿意使用 columnDefinition 参数来生成 schema2ddl。但看起来postgres不支持tinyint,但上面提到的其他数据库支持。
是否可以根据数据库类型生成不同的SQL文件。
1. 实现这一目标的最佳方法是什么?
2. 可用于此目的的最佳数据类型(存储空间最小)是什么?那会很小吗
The following JPA column definition generates an "integer" data type by default on all databases (e.g. h2, mysql, postgres)
@Column(name = "type", nullable = false)
@Type(type = "com.mycompany.hibernate.usertype.GenericEnumUserType", parameters = {
@Parameter(name = "enumClass", value = "com.mycompany.model.DegreeType"),
@Parameter(name = "identifierMethod", value = "toInt"),
@Parameter(name = "valueOfMethod", value = "fromInt") })
@NotNull
private DegreeType type;
I would like to use minimal storage for this field and hence would prefer to use the columnDefinition parameter for schema2ddl generation. But looks like tinyint is not supported in postgres, but is supported in other databases mentioned above.
Would it be possible to generate different SQL files based on the database type.
1. What would be the best approach to acheive this?
2. What would be the best data type (with minimal storage) which can be used for this purpose? Would that be smallint
发布评论
评论(1)
由于您使用的是自定义类型(为什么?),基础列定义将根据您类型的
sqlTypes()
方法的结果生成。实际的 SQL 列类型将从适当的方言中获取。因此,如果
sqlTypes()
返回new int[] {Types.TINYINT}
,PostgresQL方言会将其映射到int2
和H2 / MySQL 到tinyint
。话虽如此,我通常建议:
@Enumerated
注释内置枚举支持。将枚举值存储为字符串而不是整数。使用后者确实节省了一些空间,但它引入了一个巨大的潜在问题:3 个月(几年)后,有人通过在类型中间插入另一个枚举常量来更改代码,突然所有数据都变得无效。磁盘空间便宜;处理这样的问题不是。
<前><代码>@Enumerated(EnumType.STRING)
@Column(name = "level_type", nullable = false, length=!0)
私人 DegreeType 类型;
Since you're using custom type (why?), the underlying column definition(s) would be generated based on result of your type's
sqlTypes()
method. The actual SQL column type would be obtained from appropriateDialect
.Thus, if
sqlTypes()
were to returnnew int[] {Types.TINYINT}
, PostgresQL dialect would map it toint2
and H2 / MySQL totinyint
.All that said, I would generally recommend to:
@Enumerated
annotation.Store enum value as string rather than integer. Using the latter does conserve some space, but it introduces a huge potential problem: 3 months (years) down the line somebody changes the code by inserting another enum constant in the middle of your type and suddenly all your data becomes invalid. Disk space is cheap; dealing with issues like that isn't.