程序员

Mybatis学习02:dao层函数传入多个参数的处理方法

2017-04-14  本文已影响221人  maskwang520
对于传入一个参数的形式

dao层函数应该这么写

 public Student getStudent(@Param("id")int id);

在StudentMapper.xml应该这么写

<select id="getStudent" resultMap="User" >
        SELECT *FROM student WHERE stu_id=#{id}
    </select>

或者这种形式

<select id="getStudent" resultMap="User" >
        SELECT *FROM student WHERE stu_id=#{0}
    </select>

对于传入多个参数,也可以像上面这样处理,但是这样处理有时候显得太麻烦,我们就想传入一个list或者map.或者数组,这样就方便多啦。
  传入map的实例如下:
dao层函数是这样的:

 public List<Artical> getSomeArticals(Map<String,Integer> map);

然后在StudentMapper.xml中:

 <select id="getSomeArticals" parameterType="hashmap" resultMap="StudentArticleList">
       select student.stu_id,student.stu_name,student.stu_age,student.stu_mon,article.id,article.title,article.stuid,article.content from student,article
              where stu_id=article.stuid 
              
              <if test="stuid!=null and departmentId!=''">  
                and stu_id=#{stuid} 
              </if>  
    </select>
    

stuid直接取就行,跟传入单个一样,只要与传入进来的map.key保持一致就行。
至于list,和array,道理是一样,遍历就行

<!--List:forech中的collection属性类型是List,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 -->  
    <select id="getEmployeesListParams" resultType="Employees">  
        select *  
        from EMPLOYEES e  
        where e.EMPLOYEE_ID in  
        <foreach collection="list" item="employeeId" index="index"  
            open="(" close=")" separator=",">  
            #{employeeId}  
        </foreach>  
    </select>  
  
    <!--Array:forech中的collection属性类型是array,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 -->  
    <select id="getEmployeesArrayParams" resultType="Employees">  
        select *  
        from EMPLOYEES e  
        where e.EMPLOYEE_ID in  
        <foreach collection="array" item="employeeId" index="index"  
            open="(" close=")" separator=",">  
            #{employeeId}  
        </foreach>  
    </select>  
上一篇 下一篇

猜你喜欢

热点阅读