我们将其中一个UUID值作为binary(16)存储在mysql中。
等级库
MyTable myTable = new MyTable();` //table
SqlColumn<Long> id = column("id");` // id column
SqlColumn<UUID> myUuidColumn = column("my_uuid");` //uuid columnselect的动态sql查询。
select(myTable.id)
.from(myTable)
.where(myTable.myUuidColumn, isEqualTo(UUID.fromString("e59bf2fd-e742-4314-ab02-db195e0168c8")))
.build()
.render(RenderingStrategies.MYBATIS3);但是这是不起作用的,可能是因为UUID没有被本地支持。除了将映射程序更改为使用普通sql查询外,如何修复此问题?
发布于 2022-12-01 09:20:06
您需要编写自定义类型处理程序。
实现取决于驱动程序和/或列类型。
下面是用于使用的类型处理程序实现(即BINARY(16))。
import java.nio.ByteBuffer;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
@MappedJdbcTypes(JdbcType.BINARY)
public class UuidTypeHandler extends BaseTypeHandler<UUID> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, UUID parameter, JdbcType jdbcType) throws SQLException {
ps.setBytes(i, uuidToBytes(parameter));
}
private static byte[] uuidToBytes(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
@Override
public UUID getNullableResult(ResultSet rs, String columnName) throws SQLException {
return bytesToUuid(rs.getBytes(columnName));
}
@Override
public UUID getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return bytesToUuid(rs.getBytes(columnIndex));
}
@Override
public UUID getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return bytesToUuid(cs.getBytes(columnIndex));
}
private static UUID bytesToUuid(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
Long high = byteBuffer.getLong();
Long low = byteBuffer.getLong();
return new UUID(high, low);
}
}要在全局注册类型处理程序..。
如果使用的是application.properties.
mybatis.type-handlers-package,而不是使用SqlSessionFactoryBean.的spring、设置typeHandlersPackage或typeHandlers属性。如果由于某些原因无法在全局注册类型处理程序,则在初始化SqlColumn<UUID> myUuidColumn时可能必须传递类型处理程序的完全限定名称。
https://stackoverflow.com/questions/74638982
复制相似问题