• 09 MyBatis——Mapper的参数ParameterType


    参数类型ParameterType

    传递参数

    selectList()方法和selectOne方法,只能传一个参数:

    • 下面方法的第二个参数,即需要传入的参数(如下传入1)
    • 第一个参数为方法名。
    • session.selectOne("cn.xiaohei.mapper.PeopleMapper.selById",1);

    selectMap()方法,传递多个参数

    • 第三个参数为实参。
    • Map<String,Object> map = new HashMap<>();
    • map.put("id",1);
    • map.put("name","zhangsan");
    • session.selectOne("a.b.selById",map);//传入map

    传递的参数类型

    • 基本数据类型
    • 复杂数据类型:类和Map

    获取参数

    使用#获取

    此方法为占位方法

    下图为log4j输出的日志

    设置参数类型:这里设置了int。

    获取参数:#{0},0表示第1个参数

    如果参数是map则写为#{key}

    • 获取的方法如下
    • 其中,map为map对象,id和name为map对象中的两个属性。

    获取时的代码转换成下面这样:

     

     如果传递的参数是对象,则获取时可以#{对象的属性名}这样获取:

    <update id="updBalanceByAccno" parameterType="bank" >
             update bank set balance=balance+#{balance} where accno=#{accno}
    </update>
    

      

    如果传递的参数是多个基础类型(字符串,布尔值,数值),获取时按arg0,arg1,或param1,param2这样一次获取

    update t_user set uname=#{param1} where id=#{param2}
    

      

    推荐:或者在接口中使用@param("参数别名")来给参数起别名,而在获取时直接使用别名获取。

    List<User> selByIf(@Param("name")String name,@Param("gender") String gender);

    Mapper中:

    <select id="selByIf" resultType="User">
    		select * from User
    		<!-- OGNL表达式,直接写key或对象的属性 -->       
    		<where>
    			<if test="name!=null and name!=''">
    			    and name=#{name}
    			</if>
    			<if test="gender!=null and gender!=''">
    			    and gender=#{gender}
    			</if>
    		</where>
         </select>
    

      

    使用${}获取(很少用)

    此方式为字符串拼接,大括号中填入基础数据类型会被直接拼接近sql语句中(不是替换),所以当参数类型为对象时,大括号中可填入对象的属性名作为实参。

     

  • 相关阅读:
    [Linux] day04——Linux 入门
    react 资源汇总
    画原型图工具
    Atom 插件安装
    react 编写组件 五
    webstom 配置git 后左侧菜单栏配色调整
    Webstorm 不识别es6 import React from ‘react’——webstorm不支持jsx语法怎么办
    Es6 之for of
    一个react的完整项目展示
    前后端分离 接口管理神器——Rap本地搭建
  • 原文地址:https://www.cnblogs.com/Scorpicat/p/12410777.html
Copyright © 2020-2023  润新知