java - 如何在MyBatis中映射AtomicLong?

标签 java mybatis

我在 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/

相关文章:

collections - 如何使用 MyBatis 3.x 插入对象集合?

java - 为什么 stroke() 的 alpha 参数导致不绘制任何内容?

java - Google App Engine - 调用 getSession().invalidate();导致 App Engine 表现怪异

mybatis 返回结果映射有重复项

java - 在 Spring MVC 上部署客户端/服务器应用程序

java - Spring 4、MyBatis、带注解的多数据源

java - Hadoop 配置错误

java - Android Studio:运行我的应用程序时出现:“Could not create the Java Virtual Machine”错误

java - 将 HTML 转义字符串转换为纯 Unicode/ASCII

java - 为 mybatis 定义基本映射器时未选中覆盖?