1. 程式人生 > >mybatis查詢資料庫返回結果為空

mybatis查詢資料庫返回結果為空

用mybits查詢資料庫時,如果引數已傳入sql,sql也已經執行了,但是返回結果為空,首先保證資料庫中有對應資料,如果有對應資料仍返回null,是資料庫配置檔案有問題。解決方案如下:
1、mapper.xml檔案加入<resultMap>對映,column是資料庫中的欄位名,property是實體類javabean中的屬性,要一一對應
2、<select>標籤中不要用ResultType,要用ResultMap且名字要和<resultMap>屬性的id相同。且select語句不要用"select * from user_info",要用具體的欄位名如"select user_id,user_name from user_info"
<?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.springapp.maper.UserMapper">
    <resultMap type="User" id="BaseResultMap">
        <!--
            column:資料庫中表的欄位
            property:資料庫中表所有對映的實體類javaBean中的屬性名
         -->
        <result column="user_id" property="id"/>
        <result column="user_name" property="name"/>
    </resultMap>




    <!-- 這裡的id必須和UserMapper介面中的介面方法名相同,resultMap和上面定義的id名字相同 -->
    <select id="getUser" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select user_id,user_name from user_info where user_id=#{id}
    </select>


</mapper>