有没有一种方法可以配置 JOOQ 工具,在不提供 org.jooq.Converter 实现的情况下使用 PostgresSQL 数据库的 'forcedTypes' 标签将 smallint 转换为 Boolean?
这是当前配置的样子:
<forcedTypes>
<forcedType>
<name>BOOLEAN</name>
<types>smallint.*</types>
</forcedType>
<forcedTypes>
正在使用 JOOQ v3.9.1。 PostgreSQL v9.6.6.
不幸的是,在将信息存储到数据库中时收到下一个异常:
Caused by: org.postgresql.util.PSQLException: ERROR: column "is_complete" is of type smallint but expression is of type boolean
还尝试使用 MySQL 数据库,类似的从 tinyint 到 Boolean 的转换工作正常,没有任何错误:
<forcedTypes>
<forcedType>
<name>BOOLEAN</name>
<types>tinyint.*</types>
</forcedType>
</forcedTypes>
最佳答案
不,这不会像您期望的那样工作(也不应该)。在 jOOQ 中,如果数据库支持,BOOLEAN
数据类型将作为本地 BOOLEAN
类型绑定(bind)到 JDBC,例如PostgreSQL.
如果数据库不支持该类型(例如 MySQL/Oracle),那么 jOOQ 将绑定(bind) 0
/1
/NULL
数字值。但是您不能为支持 BOOLEAN
类型的方言强制执行此行为。但话又说回来,为什么不直接写那个转换器呢?这真的很简单。只需添加:
<forcedTypes>
<forcedType>
<userType>java.lang.Boolean</userType>
<converter>com.example.BooleanAsSmallintConverter</converter>
<!-- A bit risky. Are all smallints really booleans in your database? -->
<types>smallint.*</types>
</forcedType>
<forcedTypes>
然后:
class BooleanAsSmallintConverter extends AbstractConverter<Short, Boolean> {
public BooleanAsSmallintConverter() {
super(Short.class, Boolean.class);
}
@Override
public Boolean from(Short t) {
return t == null ? null : t.shortValue() != (short) 0;
}
@Override
public Short to(Boolean u) {
return u == null ? null : u ? Short.valueOf((short) 1) : Short.valueOf((short) 0);
}
}
关于postgresql - 使用 JOOQ 工具强制 PostgreSQL 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50963313/