在使用 MyBatis 查询时抛出 BindingException 错误。详细错误信息如下:
Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.hxstrive.mybatis.select.demo3.UserMapper is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:42)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:655)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:218)
at com.hxstrive.mybatis.select.demo3.SelectDemo3.main(SelectDemo3.java:17)
上面错误信息大概意思为“UserMapper 没有注册”。我的 Mapper XML 文件如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.select.demo2.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo2.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 根据ID查询用户信息 --> <select id="getUserById" parameterType="int" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where `user_id`=#{userId,jdbcType=INTEGER} </select> </mapper>
上面配置信息中,“namespace="com.hxstrive.mybatis.select.demo2.UserMapper"”将 Mapper XML 文件对应的 Mapper Java 接口文件写错了。
修改如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.select.demo3.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo3.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 根据ID查询用户信息 --> <select id="getUserById" parameterType="int" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where `user_id`=#{userId,jdbcType=INTEGER} </select> </mapper>
上面 com.hxstrive.mybatis.select.demo3.UserMapper 和本配置文件在同一个包下面。
点击学习 MyBatis 教程,了解更多的 MyBatis 知识!