JDBI 仅针对 JDBC 公开的类型公开基于显式类型的绑定。 JDBC 不公开用于绑定的 UUID 类型,因此默认将其设置为对象。不幸的是,JDBC 没有提供显式的 UUID 绑定机制,因此通过 String 可能是最可移植的方式:-(
如果你想在Java中将其绑定为UUID并在内部将其转换为String,有两条路径。第一个,如果你always想要将 UUID 绑定为字符串是使用 ArgumentFactory,请参阅https://github.com/brianm/jdbi/blob/master/src/test/java/org/skife/jdbi/v2/sqlobject/TestRegisterArgumentFactory.java举个例子。
第二种是,如果您只想在特定情况下执行此操作,请创建自定义 Binder,例如使用http://jdbi.org/sql_object_api_argument_binding/
使用 ArgumentFactory 实现从 UUID 到字符串的全局绑定的示例:
UUIDArgumentFactory.java:
public class UUIDArgumentFactory implements ArgumentFactory<UUID> {
@Override
public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) {
return value instanceof UUID;
}
@Override
public Argument build(Class<?> expectedType, UUID value, StatementContext ctx) {
return new UUIDArgument(value);
}
}
UUIDArgument.java:
public class UUIDArgument implements Argument {
private final UUID value;
public UUIDArgument(UUID value) {
this.value = value;
}
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setString(position, value.toString());
}
}
登记:
final DatabaseFactory factory = new DatabaseFactory(environment);
final Database db = factory.build(configuration.getDatabaseConfiguration(), "sqlserver");
db.registerArgumentFactory(new UUIDArgumentFactory());