有没有办法配置JOOQ工具,使用PostgresSQL数据库的“forcedTypes”标记将smallint转换为Boolean,而不提供org.JOOQ.Converter实现?
当前配置如下:

<forcedTypes>
    <forcedType>
        <name>BOOLEAN</name>
        <types>smallint.*</types>
    </forcedType>
<forcedTypes>

正在使用JOOQ v3.9.1。
PostgreSQL第9.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数据类型将作为原生类型绑定到JDBC,例如PostgreSQL。
如果数据库不支持该类型(例如MySQL/Oracle),那么jOOQ将绑定BOOLEAN/0/1数值。但是,对于支持NULL类型的方言,不能强制执行此行为。但再说一遍,为什么不直接写那个转换器呢?很简单。只需添加:

<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/

10-14 00:48