Using custom converter for JOOQ's DSL.val()

怎甘沉沦 提交于 2019-12-24 16:22:59

问题


In my application, a piece of content is identified using java.util.UUID. While storing information in the database, the corresponding MySQL data type that I am using is BINARY(16). The default JDBC data type for BINARY is byte[]. So I have a custom org.jooq.Converter to translate between UUID and byte[].

I have a use-case in which I need to copy a record from a table into the same table but copy only certain columns and not all. In the original question I had posted here, The following was the solution

public void copy(UUID source, UUID target) {
    jooq.insertInto(PERSON)
            .columns(PERSON.ID, PERSON.FNAME, PERSON.LNAME)
            .select(select(val(target), PERSON.FNAME, PERSON.LNAME)
                   .from(PERSON)
                   .where(PERSON.ID.eq(source)))
            .execute();
} 

But executing this piece of code led to an exception

Data truncation: Data too long for column 'id' at row 1

I figured out that DSL.val() was not using the custom converter I had in place for converting UUID to byte[]. How can I force the DSL.val() function to use the custom converter?


回答1:


Solution: Use DSL.val(java.lang.Object value, DataType<T> type) instead of just DSL.val(java.lang.Object value)

Following is the updated code snippet

public void copy(UUID source, UUID target) {
    DataType<UUID> uuidType = SQLDataType.BINARY
                                .asConvertedDataType(new UuidBinaryConverter());
    jooq.insertInto(PERSON)
            .columns(PERSON.ID, PERSON.FNAME, PERSON.LNAME)
            .select(select(val(target, uuidType), PERSON.FNAME, PERSON.LNAME)
                   .from(PERSON)
                   .where(PERSON.ID.eq(source)))
            .execute();
} 


来源:https://stackoverflow.com/questions/50741895/using-custom-converter-for-jooqs-dsl-val

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