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”
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值