When using the
@ColumnName annotation, I have typically placed it on a field. Here is an example from the
documentation showing this:
public class User {
@ColumnName("user_id")
public int id;
public String name;
}
This all worked as expected with text, numbers and dates, until I tried to use a Java boolean field to receive the value of a MySQL tinyint(1) column value.
When using only JDBC, the mapping from tinyint(1) to boolean worked as expected:
boolean admin = resultSet.getBoolean("is_admin");
In this case, however, when using Jdbi, the getter did not fire:
The field:
@ColumnName("is_admin")
private boolean admin;
My Jdbi handler:
Jdbi jdbi = Jdbi.create(url, user, pass);
List<User> users = jdbi.withHandle(handle -> handle
.select("select user_id, is_admin from my_db.user")
.mapToBean(User.class)
.list());
The solution was straightforward: Move the annotation to the getter (or setter):
@ColumnName("is_admin")
// using getAdmin() behaves the same as using isAdmin()
public boolean isAdmin() {
return admin;
}
The documentation also mentions the following:
The @ColumnName annotation can be placed on either the getter or setter
method.
But I read that as "can also be placed..." rather than "must always be placed...".
Is this the expected behavior: That you must place the annotation on a getter/setter in some specific cases - but you can otherwise place the annotation on the field name?
Or am I making some other mistake in my approach?
- - -
I am using:
- MySQL DB 8.0.18
- MySQL Connector 8.0.23
- Java 15
- Jdbi 3.18.0