我在 MyBatis 中使用 xml 映射器文件将所有 POJO 类推送到数据库中。然而,其中一个对象有一个 AtomicLong 作为字段,而 MyBatis 似乎不知道如何处理它。
我尝试为 POJO 类做一个非常标准的映射器,并且有一个如下所示的 resultMap:
<resultMap id="result" type="MyPojo">
<result property="myAtomicLongVal" column="myLongValColumn"/>
</resultMap>
当我这样做时,我收到一条错误消息。
org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalStateException: No typehandler found for property myAtomicLongVal
最佳答案
AtomicLong
没有内置类型处理程序,因此您可能需要编写一个。
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
@MappedTypes(AtomicLong.class)
public class AtomicLongTypeHandler
extends BaseTypeHandler<AtomicLong>{
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
AtomicLong parameter, JdbcType jdbcType)
throws SQLException {
ps.setLong(i, parameter.get());
}
@Override
public AtomicLong getNullableResult(ResultSet rs,
String columnName) throws SQLException {
return new AtomicLong(rs.getLong(columnName));
}
@Override
public AtomicLong getNullableResult(ResultSet rs,
int columnIndex) throws SQLException {
return new AtomicLong(rs.getLong(columnIndex));
}
@Override
public AtomicLong getNullableResult(CallableStatement cs,
int columnIndex) throws SQLException {
return new AtomicLong(cs.getLong(columnIndex));
}
}
您可以在配置中全局注册类型处理程序。例如
<typeHandlers>
<typeHandler handler="pkg.AtomicLongTypeHandler" />
</typeHandlers>
结果图应该按原样工作。
关于java - 如何在MyBatis中映射AtomicLong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56637758/