Mybatis 查询数据返回基本类型数组

1. mybatis 查询数据的时候返回类型不能是基本类型的数组。如果是基本类型的数组会报类型转换错误。

//StudentMapper
public interface StudentMapper {
    int[] getAllStudentIds();
}

//StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.morris.dao.StudentMapper">
    <resultMap id="orderInfo" type="com.morris.po.OrderInfo">
        <id property="id" column="order_id"/>
        <result property="orderNumber" column="order_number"/>
        <association property="orderAddress" javaType="com.morris.po.OrderAddress">
            <result property="region" column="region"/>
            <result property="district" column="district"/>
            <result property="city" column="city"/>
            <result property="street" column="street"/>
        </association>
    </resultMap>

    <select id="getAllStudentIds" resultType="int">
        select id
            from student;
    </select>

</mapper>

//验证
 public static void main(String [] args) {
        SqlSession session = getSqlSession();
        StudentMapper sm = session.getMapper(StudentMapper.class);
        int[] ids = sm.getAllStudentIds();
        for (int i : ids) {
            System.out.println(i);
        }
}
运行程序会抛出ClassCastException
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
    at org.apache.ibatis.binding.MapperMethod.convertToArray(MapperMethod.java:141)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:124)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
    at com.sun.proxy.$Proxy0.getAllStudentIds(Unknown Source)
    at com.morris.util.MybatisUtil.main(MybatisUtil.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
  1. 解决方案
    1. 接口中返回数据 用包装类来接收
      1. Integer[] getAllStudentIds();
      2. xml 配置中resultType=”int” 改成 resultType=”java.lang.Integer”
    2. 接口中用list 来接收
      1. List<Integer> getAllStudentIds();
      2. xml 配置中resultType=”int” 改成 resultType=”java.lang.Integer”

猜你喜欢

转载自blog.csdn.net/diy0118/article/details/71173511