JOOQ forced type code generation

此生再无相见时 提交于 2019-12-12 11:34:28

问题


I'm having some problems generating code using forced types (JOOQ 3.3, Postgres 9.3).

Trying to convert sql timestamp to joda DateTime, leads me to compilation errors.

My table:

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

and my .xml config:

// [...]
<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 class:

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;
    }
}

So, BOOK.DATE_PUBLISHED is being generated like this:

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());

which leads to compilation error:

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

I know i can change type of DATE_PUBLISHED to TableField<BookRecord,DateTime> and refactor the code, but i dont want to patch the generated classes manually.

Any ideas what am i doing wrong?


回答1:


The <name/> element of your <customType/> should refer to the <U> type (user type) of your Converter<T, U>, not to the <T> type (database type). So if you write this:

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

Then you're really just registering a Converter<Timestamp, Timestamp>. Try this instead:

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

Note that your converter should also correctly handle null values:

@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());
}


来源:https://stackoverflow.com/questions/23979524/jooq-forced-type-code-generation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!