Fork me on GitHub

Mybatis————动态SQl查询问题

Mybatis————动态SQl查询问题

今天学习Mybatis框架时,动态SQL查询报如下异常:

1
2
org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'net.zzqd.mybatis.mapper.UserMapper.selectStateUserName'. It's likely that neither a Result Type nor a Result Map was specified.

经过万能的百度,了解到原来是mapper.xml里没加parameterType和resultType属性,前面的语句没加这两个属性也能执行,暂时不知道是为什么。

1
2
3
4
5
6
7
8
9
10
11
12
13
	异常代码
<!-- 动态sql -->
<select id="selectStateUserName" >
select * from user
where state=1
<if test="value !=null and value != ''">
AND name like '%${value}%'
</if>

<!-- <if test="value !=null and value != ''"> -->
<!-- AND name like #{name} -->
<!-- </if> -->
</select>

添加属性后就ok了

1
2
3
4
5
6
7
8
9
10
11
12
	<!--     动态sql -->
<select id="selectStateUserName" resultType="User" parameterType="string">
select * from user
where state=1
<if test="value !=null and value != ''">
AND name like '%${value}%'
</if>

<!-- <if test="value !=null and value != ''"> -->
<!-- AND name like #{name} -->
<!-- </if> -->
</select>

经过了解Mybatis开发以下几点规范:

1、在mapper.xml中namespace等于mapper接口地址

2、mapper.java接口中的方法名和mapper.xml中statement的id一致

3、mapper.java接口中的方法输入参数类型和mapper.xml中statement的parameterType指定的类型一致。

4、mapper.java接口中的方法返回值类型和mapper.xml中statement的resultType指定的类型一致。