动态SQL之内置参数_parameter的使用讲解

_parameter表示传入SQL中整体参数。下面以查询为例

示例一:

假设用name查PERSON表,定义对应的DAO接口为:

package com.lzj.mybatis.dao;
import java.util.List;
import com.lzj.mybaits.bean.Person;
public interface PersonDao {
    public List
 
   getPersons(String username);
}
 

DAO接口对应的mapper文件为:

<mapper namespace="com.lzj.mybatis.dao.PersonDao">  
    <select id="getPersons" resultType="com.lzj.mybaits.bean.Person">
        select * from PERSON
        <!--此时_parameter内置参数中的值为接口中传入的username的值-->
        <if test="_parameter != null">
            where name=#{name}
        </if>
    </select>
</mapper>

示例二:

本示例DAO接口中传入一个person对象,如果person对象不为空,则用name查PERSON表。首先定义DAO接口:

package com.lzj.mybatis.dao;
import java.util.List;
import com.lzj.mybaits.bean.Person;
public interface PersonDao {
    public List
 
   getPersons(Person person);
}
 

DAO接口对应的mapper文件不变:

<mapper namespace="com.lzj.mybatis.dao.PersonDao">  
    <select id="getPersons" resultType="com.lzj.mybaits.bean.Person">
        select * from PERSON
        <!--此时_parameter内置参数中的值为接口中传入的person对象中的id、name、age的整体值,也就是说,不管接口中传入的多少数据,都整体的放在了_parameter内置参数中-->
        <if test="_parameter != null">
            where name=#{name}
        </if>
    </select>
</mapper>

综合上面两个示例,

_parameter:代表DAO接口传入的整个参数

如果DAO接口就传入了单个参数:_parameter就是这个参数; 如果DAO接口就传入了多个参数:参数会被封装为一个map,_parameter就是代表这个map

注意:

在mapper文件中定义sql语句时,有些sql语句需要返回值,例如 等标签语句,返回值的类型一般定义在resultType或resultMap中,如果返回类型为自定义的对象类型,像本例中的Person类,那么这个类中一定不要定义有参的构造器,需要定义get和set方法。因为mybatis在处理完sql后,把返回的数据是通过set方法放到Person对应的对象中的,而不是通过有参构造器。如果定义了有参构造器,则会包如下错误:

## Cause: org.apache.ibatis.reflection.ReflectionException: Error instantiating class com.lzj.mybaits.bean.Person with invalid types () or values (). Cause: java.lang.NoSuchMethodException: com.lzj.mybaits.bean.Person.
 
  ()
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:95)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:124)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:90)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:40)
    at com.sun.proxy.$Proxy0.getPersons(Unknown Source)
    at com.lzj.mybatis.example.MybaitsTest.testGetPersons(MybaitsTest.java:43)
    at com.lzj.mybatis.example.MybaitsTest.main(MybaitsTest.java:19)

 

上述错误表示com.lzj.mybaits.bean.Person. ()初始化方法异常

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐