0
votes

I'm using xml mapper files in MyBatis to push all of my POJO classes into a database. However, one of these objects has an AtomicLong as a field, and MyBatis doesn't seem to know how to handle it.

I tried doing a pretty standard mapper for the POJO class, and had a resultMap that looked like this:

<resultMap id="result" type="MyPojo">
   <result property="myAtomicLongVal" column="myLongValColumn"/>
</resultMap>

When I do this, I get an error message.

org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML.  Cause: java.lang.IllegalStateException:  No typehandler found for property myAtomicLongVal
1

1 Answers

1
votes

There is no built-in type handler for AtomicLong, so you may need to write one.

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));
  }
}

You can register the type handler globally in the config. e.g.

<typeHandlers>
  <typeHandler handler="pkg.AtomicLongTypeHandler" />
</typeHandlers>

The result map should work as-is.