在MyBatis中使用PostgreSQL的UUID類型,需要進(jìn)行如下配置:
<typeHandlers>
<typeHandler handler="com.example.UUIDTypeHandler"/>
</typeHandlers>
public class UUIDTypeHandler implements TypeHandler<UUID> {
@Override
public void setParameter(PreparedStatement ps, int i, UUID parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, Objects.toString(parameter, null));
}
@Override
public UUID getNullableResult(ResultSet rs, String columnName) throws SQLException {
String uuid = rs.getString(columnName);
return (uuid != null) ? UUID.fromString(uuid) : null;
}
@Override
public UUID getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String uuid = rs.getString(columnIndex);
return (uuid != null) ? UUID.fromString(uuid) : null;
}
@Override
public UUID getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String uuid = cs.getString(columnIndex);
return (uuid != null) ? UUID.fromString(uuid) : null;
}
}
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO users (id, name) VALUES (#{id, typeHandler=com.example.UUIDTypeHandler}, #{name})
</insert>
這樣就可以在MyBatis中使用PostgreSQL的UUID類型了。需要注意的是,如果數(shù)據(jù)庫中的UUID字段不是以String形式存儲(chǔ)的,需要根據(jù)實(shí)際情況調(diào)整TypeHandler的實(shí)現(xiàn)方式。