日常开发中,常在mapper接口层中 用map存值,也用map返回值。有时当数据库表中的某一个字段为空时,返回的map不会映射成键值对。
直接上代码:
1.mapper接口层
@Repository
public interface UserMapper {
List<Map> selectUser();
}
2.mapper.xml映射文件,有一点注意的是,xml文件中sql语句最后面最好别加 分号 ,之前在开发中遇到过 分号问题,调试了很久才发现是这个错误。
<mapper namespace="com.swx.dao.UserMapper">
<select id = "selectUser" resultType = "map" >
select username,password from user order by id;
</select>
</mapper>
解决的方案:
一。如果用springboot整合mybatis框架 。
在application.properties文件中 添加 mybatis.configuration.callSettersOnNulls=true 可以解决用sql查数据库返回map允许字段为空的也映射出来。如果写的存储过程查询数据库,设置这些似乎都没用(因为我实际开发项目中是用的存储过程设置了不生效)。
二。如果直接用的mybatis-config.xml文件。
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true"/>
</settings>
</configuration>
三。如果不嫌麻烦可以直接定义一个resultMap标签然后创建一个实体类,把要查询的数据库字段和实体类映射起来,直接返回实体类。
<resultMap id="userMap" type="com.swx.entity.User">
<result property="id" column="id"></result>
<result property="username" column="username"></result>
<result property="password" column="password"></result>
</resultMap>
<select id="selectUser" resultMap="userMap" >
select username,password from user order by id;
</select>
mapper接口层就是 public List<User> selectUser();这样返回的数据就是不管有没有空直接对应上来了。
以上希望对你有帮助。