Jooq currently does not support JSR 310 types和 support will not come until v3.8 .
使用简单的转换器通常可以工作,除了某些类型,例如 postgres 的 TIMESTAMP WITH TIME ZONE
,它需要自定义绑定(bind)。所以我尝试编写一个,但生成的 XxxRecord
类仍然为我的数据库中的 TIMESTAMP WITH TIME ZONE
字段使用 Timestamp
数据类型。
我需要在下面的代码中更改什么才能在 jooq 生成的类中将 postgres 的 TIMESTAMP WITH TIME ZONE
视为 Instant
?
转换器
public class TimestampConverter implements Converter<Timestamp, Instant> {
@Override public Instant from(Timestamp ts) {
return ts == null ? null : ts.toInstant();
}
@Override public Timestamp to(Instant instant) {
return instant == null ? null : Timestamp.from(instant);
}
@Override public Class<Timestamp> fromType() { return Timestamp.class; }
@Override public Class<Instant> toType() { return Instant.class; }
}
自定义绑定(bind)
public class TimestampBinding implements Binding<Timestamp, Instant> {
private static final Converter<Timestamp, Instant> converter = new TimestampConverter();
private final DefaultBinding<Timestamp, Instant> delegate =
new DefaultBinding<> (converter());
@Override public Converter<Timestamp, Instant> converter() { return converter; }
@Override public void sql(BindingSQLContext<Instant> ctx) throws SQLException {
delegate.sql(ctx);
}
//etc. same for all other overriden methods.
}
pom.xml(摘录)
<customType>
<name>java.time.Instant</name>
<type>java.time.Instant</type>
<binding>xxx.TimestampBinding</binding>
</customType>
...
<forcedType>
<name>java.time.Instant</name>
<types>timestamp with time zone</types>
</forcedType>
最佳答案
一种方法是转义 <types>
中的空格带有反斜杠,如下所示:
<types>timestamp\ with\ time\ zone</types>
<types>
中不能只有常规空格因为默认情况下,org.jooq.util.AbstractDatabase
将parse regular expressions in COMMENTS mode这使得创建的 Pattern
对象 ignore whitespace在你的正则表达式中。你也可以做类似 <types>timestamp.*zone</types>
的事情,或指定您自己的 <regexFlags>
.
以下是完整的 Maven jooq-codegen-maven
适合我的插件标签。我还找到了 <binding>
没有必要。
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>3.7.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<jdbc>
<driver>org.postgresql.Driver</driver>
<url>jdbc:postgresql:postgres</url>
<user>postgres</user>
<password>mypass</password>
</jdbc>
<generator>
<database>
<customTypes>
<customType>
<name>Instant</name>
<type>java.time.Instant</type>
<converter>xxx.TimestampConverter</converter>
</customType>
</customTypes>
<forcedTypes>
<forcedType>
<name>Instant</name>
<types>timestamp\ with\ time\ zone</types>
</forcedType>
</forcedTypes>
<name>org.jooq.util.postgres.PostgresDatabase</name>
<includes>author</includes>
<excludes/>
<inputSchema>public</inputSchema>
</database>
<target>
<packageName>xxx.table</packageName>
<directory>target/generated-sources/jooq</directory>
</target>
</generator>
</configuration>
</plugin>
关于java - postgres 中 "timestamp with time zone"类型的 Jooq 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173842/