【问题标题】:JOOQ forced type code generationJOOQ 强制类型代码生成
【发布时间】:2014-07-21 16:26:20
【问题描述】:

我在使用强制类型(JOOQ 3.3、Postgres 9.3)生成代码时遇到了一些问题。

尝试将 sql 时间戳转换为 joda DateTime,导致编译错误。

我的桌子:

CREATE TABLE book
(
  // [...]
  date_published timestamp without time zone,
  // [...]
);

和我的 .xml 配置:

// [...]
<customTypes>
  <customType>
   <name>java.sql.Timestamp</name>
   <converter>com.plannow.jooq.converters.DateTimeConverter</converter>
  </customType>         
</customTypes>
<forcedTypes>
  <forcedType>
   <name>java.sql.Timestamp</name>
   <expression>.*\.date_.*</expression>
   <types>.*</types>
  </forcedType>
</forcedTypes>
// [...]

DateTimeConverter 类:

public class DateTimeConverter implements Converter<Timestamp, DateTime>
{

    @Override
    public DateTime from(Timestamp databaseObject)
    {
        return new DateTime(databaseObject);
    }

    @Override
    public Timestamp to(DateTime userObject)
    {
        return new Timestamp(userObject.getMillis());
    }

    @Override
    public Class<Timestamp> fromType()
    {
        return Timestamp.class;
    }

    @Override
    public Class<DateTime> toType()
    {
        return DateTime.class;
    }
}

所以,BOOK.DATE_PUBLISHED 是这样生成的:

public final org.jooq.TableField<com.plannow.jooq.db.tables.records.BookRecord, java.sql.Timestamp> DATE_PUBLISHED = createField("date_published", org.jooq.impl.SQLDataType.TIMESTAMP, this, "", new com.plannow.jooq.converters.DateTimeConverter());

导致编译错误:

Type mismatch: cannot convert from TableField<BookRecord,DateTime> to TableField<BookRecord,Timestamp>.

我知道我可以将DATE_PUBLISHED 的类型更改为TableField&lt;BookRecord,DateTime&gt; 并重构代码,但我不想手动修补生成的类。

任何想法我做错了什么?

【问题讨论】:

    标签: java postgresql type-conversion jooq


    【解决方案1】:

    &lt;customType/&gt;&lt;name/&gt; 元素应该引用 Converter&lt;T, U&gt;&lt;U&gt; 类型(用户类型),而不是 &lt;T&gt; 类型(数据库类型)。所以如果你写这个:

    <customTypes>
      <customType>
       <name>java.sql.Timestamp</name>
       <converter>com.plannow.jooq.converters.DateTimeConverter</converter>
      </customType>         
    </customTypes>
    

    那么您实际上只是在注册Converter&lt;Timestamp, Timestamp&gt;。试试这个:

    <customTypes>
      <customType>
       <name>org.joda.time.DateTime</name>
       <converter>com.plannow.jooq.converters.DateTimeConverter</converter>
      </customType>         
    </customTypes>
    

    请注意,您的转换器还应正确处理 null 值:

    @Override
    public DateTime from(Timestamp t)     {
        return t == null ? null : new DateTime(t);
    }
    
    @Override
    public Timestamp to(DateTime u) {
        return u == null ? null : new Timestamp(u.getMillis());
    }
    

    【讨论】:

    • 非常感谢您的快速回答。我真的不知道我怎么会错过`` 注释。无论如何再次感谢
    • @user3215799:它发生在最好的地方 ;-)
    猜你喜欢
    • 2021-02-20
    • 2014-09-09
    • 2017-12-03
    • 2017-08-13
    • 2020-01-23
    • 2014-03-06
    • 2017-11-28
    • 2016-06-12
    • 2020-12-23
    相关资源
    最近更新 更多