有没有办法配置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); } }