文章目录
- mybatis中的常见错误:
- 错误1:There is no getter for property named '......' in 'class ...'
- 错误2:Expected one result (or null) to be returned by selectOne(), but found: 7
- 错误3:A query was run and no Result Maps were found for the Mapped Statement 'test.insertUser!selectKey'. It's likely that neither a Result Type nor a Result Map was specified.
- 错误4:Type interface com.sniper.mybatis.mapper.UserMapper is not known to the MapperRegistry.
- 错误5:Could not resolve type alias 'users'. Cause: java.lang.ClassNotFoundException: Cannot find class: users
- 错误5:Mapping is missing column attribute for property null
- 问题一 (不存在的列)
- 问题二 (模棱两可的字段)
- 问题三 (不一致的接收对象)
- 问题四 (重复的方法名)
- 问题五 (重复的方法名)
- 问题六 (不存在的属性)
mybatis中的常见错误:
错误1:There is no getter for property named ‘…’ in ‘class …’
### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException:
There is no getter for property named 'values' in 'class java.lang.String'
### Cause: org.apache.ibatis.reflection.ReflectionException:
There is no getter for property named 'values' in 'class java.lang.String'
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:122)
......
错误原因:Mapper文件中 #{id}, #{title}, #{type} …接收输入参数的内容有单词拼写错误
<insert id="insertDutyReceiveMain"
parameterType="com.dcits.forestry.duty.bean.DutyReceiveMain">
INSERT INTO DUTY_RECEIVE_MAIN(
ID,TITLE,'TYPE',ISSUE,SEND_ORGAN_ID,SEND_ORGAN_NAME,SEND_TIME,RECEIVE_ORGAN_ID,RECEIVE_ORGAN_NAME,STATUS,SIGN_TIME,ARCHIVE_TIME,REJECTION_REASON,
DP_ID, KEYWORD, MESSAGE_TYPE,ISSUED_PERSONNEL,PHONENUMBER
)
VALUES(
#{id},#{title},#{type},#{issue},#{sendOrganId},#{sendOrganName},#{sendTime},#{receiveOrganId},#{receiveOrganName},#{status},#{signTime},#{archiveTime},#{rejectionReason},#{dpId},#{keyWord},#{messageType},#{issuedPersonnel},#{phoneNumber}
)
</insert>
错误2:Expected one result (or null) to be returned by selectOne(), but found: 7
org.apache.ibatis.exceptions.TooManyResultsException:
Expected one result (or null) to be returned by selectOne(), but found: 7
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
at com.sniper.mybatis.first.MybatisFirst.findUserByName(MybatisFirst.java:86)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
......
错误原因:结果集中包含了多条记录,不应该使用selectOne,应该使用selectList
<!-- 错误写法:
List<User> list = sqlSession.selectOne("test.findUserByName", "小明");
-->
List<User> list = sqlSession.selectList("test.findUserByName", "小明");
错误3:A query was run and no Result Maps were found for the Mapped Statement ‘test.insertUser!selectKey’. It’s likely that neither a Result Type nor a Result Map was specified.
### Error updating database. Cause: org.apache.ibatis.executor.ExecutorException:
A query was run and no Result Maps were found for the Mapped Statement 'test.insertUser!selectKey'.
It's likely that neither a Result Type nor a Result Map was specified.
### The error may exist in sqlmap/User.xml
### The error may involve test.insertUser!selectKey
### The error occurred while handling results
### SQL: SELECT LAST_INSERT_ID()
### Cause: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'test.insertUser!selectKey'. It's likely that neither a Result Type nor a Result Map was specified.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:172)
.....
错误原因:Mapper文件中没有指定返回的类型
<select id="getTotalNumber" resultType="int"
parameterType="hashMap">
SELECT * FROM RECEIVE_MAIN
<where>
<if test="id!=null and id!=''"> AND ID=#{id} </if>
<if test="title!=null and title!=''"> AND TITLE=#{title} </if>
<if test="type!=null and type!=''"> AND TYPE=#{type} </if>
</where>
</select>
错误4:Type interface com.sniper.mybatis.mapper.UserMapper is not known to the MapperRegistry.
org.apache.ibatis.binding.BindingException: Type interface com.sniper.mybatis.mapper.UserMapper is not known to the MapperRegistry.
at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47)
at org.apache.ibatis.session.Configuration.getMapper(Configuration.java:689)
at org.apache.ibatis.session.defaults.DefaultSqlSession.getMapper(DefaultSqlSession.java:250)
......
错误原因:mapper.xml问没有注册到到mybatis的配置文件中
<pre name="code" class="html"><!-- 加载映射文件 -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
错误5:Could not resolve type alias ‘users’. Cause: java.lang.ClassNotFoundException: Cannot find class: users
### Error building SqlSession.
### The error may exist in mapper/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException:
Error parsing SQL Mapper Configuration.
Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'users'.
Cause: java.lang.ClassNotFoundException: Cannot find class: users
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:82)
......
错误原因:类路径或者别名写错了
<select id="findUserByName" parameterType="java.lang.String" resultType="user">
<!-- 使用${}会有sql注入的问题 -->
<!-- SELECT * FROM USER WHERE username LIKE '%${value}%' -->
SELECT * FROM USER WHERE username LIKE '%'||#{value}||'%'
</select>
错误5:Mapping is missing column attribute for property null
### Error building SqlSession.
### The error may exist in com/sniper/mybatis/mapper/OrdersCustomMapper.xml
### The error occurred while processing mapper_resultMap[OrdersUserResultMap]_association[user]
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML.
Cause: java.lang.IllegalStateException: Mapping is missing column attribute for property null
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:82)
......
错误原因:
映射文件格式有问题
1.检查mapper.xml文件里的方法有没有resultType
2.如果是注解方式请检查mapper的方法返回值类型
<resultMap
type="com.dcits.forestry.duty.bean.DutyReceiveMain"
id="dutyReceiveMain">
<result property="id" column="ID" />
<result property="title" column="TITLE" />
<result property="sendTime" column="SEND_TIME" />
</resultMap>
问题一 (不存在的列)
Unknown column ‘name’ in ‘field list’
这个问题在使用Mybatis时,属于比较常见的低级错误。
问题描述:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'name' in 'field list'
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'name' in 'field list'
; bad SQL grammar []
主要原因:
Mybatis XML中的SQL语句查询的列,不在数据库中。
新增SQL语句中的列不在数据库中,或列对应的值,数据类型不一致。
解决办法: 根据项目实际情况,通常有以下三种解决办法:
修改SQL语句中,将不存在的列从语句中去掉。
在数据库中,新增该不存在的列。
在新增时,不要使用中文符号的``表示字符串。也就是~符号对应的键。
注意事项:
删除了数据库中的列。在SQL语句中,没有同步删除该字段的。会比较容易出现该问题。
这里还有一个比较特殊的场景,会导致上述问题的发生。
以下SQL在windows环境下会显示上述错误,不会进行新增操作:
insert into t_base_user(name,created_time,updated_time)values(name
,now(),now());
但在Linux环境下,其会进行新增操作。但是 name 的值不会进行新增。
问题二 (模棱两可的字段)
Column ‘oid’ in field list is ambiguous
问题描述:
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'oid' in field list is ambiguous
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'oid' in field list is ambiguous; SQL []; Column 'oid' in field list is ambiguous
主要原因:连接查询时没有指定共有字段的所属表。 也就是说。A表有name字段,B表也有name字段。连接查询时查询name时。SQL服务器不知道返回哪个表的name字段导致。
解决方案:明确查询列的所属表。
例如:
表结构在文章最后,有兴趣的童鞋可以测试。执行以下SQL即可还原上述问题,
select u.id,name from t_base_user as u RIGHT JOIN
t_base_user_role as r on u.id = r.user_id
注意事项: 将上述语句中的 u.id 修改为 id 也能正常运行。因为id不是公共字段,只有user表才id字段。
问题三 (不一致的接收对象)
TooManyResultsException:
问题描述:
Exception in thread "main" org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 9
主要原因:在接口中指定单个返回对象。但执行SQL后,有多条符合条件的数据。
解决方案:
根据实际的业务场景,通常有以下两种解决办法:
修改接口的返回结果为集合。
修改SQL语句使其只返回一个符合条件的结果。
问题四 (重复的方法名)
Mapped Statements collection already contains value for UserDao.getUserByName
描述:
Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.lang.RuntimeException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for UserDao.getUserByName
原因: 在UserDao中,有两个同名方法getUserByName导致。
解决办法: 重命名其中一个方法名即可。
问题五 (重复的方法名)
Mapped Statements collection does not contain value for ‘xxx’
描述:
Cause: java.lang.IllegalArgumentExeception: Mapped Statements collection does not contain value for 'xxx'
原因: "Mapper的结果不包含 ‘xxx’ ",因为xxx在全局配置文件中没有加载该类的mapper.xml
解决办法: 重命名其中一个方法名即可。
问题六 (不存在的属性)
There is no getter for property named ‘username’ in ‘com.andyqian.user.bean.User’
描述:
Error updating database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'username' in 'com.andyqian.user.bean.User'
Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'education' in 'class com.andyqian.user.bean.User'
原因: SQL中查询的列,在其实体对象中不存在对应的属性。
解决办法: 在对应的实体对象上,添加上缺失的属性即可。
数据结构
在本文中,所有测试均使用以下表结构。SQL语句如下所示,有兴趣的童鞋可以进行实验。
create table t_base_user_role(
oid bigint(20) not null primary key auto_increment comment "",
user_id bigint(20) null comment "",
name varchar(50) null comment "",
create_time datetime null comment "",
update_time datetime null comment ""
)
CREATE TABLE `t_base_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb4 DEFAULT NULL,
`created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deleted` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
最后
上述几个都属于比较常见且容易解决的问题。基本上能够通过描述,就能定位到问题的原因。之所以能够发生。简答归纳为以下两点:
xml文件中的SQL,没有在数据库中执行。
没有写单元测试。