加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用JOOQ工具强制PostgreSQL类型转换

发布时间:2020-12-13 15:53:46 所属栏目:百科 来源:网络整理
导读:有没有办法配置JOOQ工具,使用PostgresSQL数据库的’forcedTypes’标签将smallint转换为Boolean,而不提供org.jooq.Converter实现? 这是当前配置的样子: forcedTypes forcedType nameBOOLEAN/name typessmallint.*/types /forcedTypeforcedTypes 正在使用JOO
有没有办法配置JOOQ工具,使用PostgresSQL数据库的’forcedTypes’标签将smallint转换为Boolean,而不提供org.jooq.Converter实现?

这是当前配置的样子:

<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类型绑定到JDBC,例如,PostgreSQL的.

如果数据库不支持该类型(例如MySQL / Oracle),则jOOQ将绑定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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读