Jdbi has a
@ColumnName annotation which can be used to map a table’s column name to the corresponding field of a JavaBean. See http://jdbi.org/#_beanmapper.
The examples given in the documentation show how to use the annotation with a field name:
And also with a constructor:
In my case, I tried using the annotation on a
The related column was in a MySQL 8 table, and was defined as follows:
When using plain JDBC, the
tinyint(1) data was correctly converted from 0 and 1 to
However, when using Jdbi, this did not work and the annotation had no effect.
Specifically, when reading data from the table, the related getter was never called - and therefore all values were set to
false (the default value for a Java
The other table column
user_id (a string) was handled correctly.
There is one note in the Jdbi documentation which states:
@ColumnNameannotation can be placed on either the getter (or setter) method, instead of on the field declaration.
When I moved the annotation to the getter, the problem was resolved.
Here is the full
User bean, for reference:
Conclusion: From now onwards, I will always place this annotation on a field’s getter or setter.
The reason my code worked for column name
user_id mapping to field name
userIDis that I am using one of Jdbi’s “reflective mappers” - the bean mapper - and these mappers automatically map
snake_case column names to
camelCase field names.
From the Jdbi documentation:
Reflective mappers treat column names as bean property names (BeanMapper), constructor parameter names (ConstructorMapper), or field names (FieldMapper).
Reflective mappers are snake_case aware and will automatically match up these columns to camelCase field/argument/property names.
However, the nature of the snake-to-camel conversion does seem to have one subtlety. In my case, my database column is:
and my field name is:
Strict conversion from snakecase to camelcase should produce this:
userID works correctly.
This is because the converter is case insensitive.