zoukankan      html  css  js  c++  java
  • Mybatis传递多个参数的几种方式

    Mybatis传递多个参数的几种方式

    顺序传参法

    public User selectUser(String name, int deptId);
    
    <select id="selectUser" resultMap="UserResultMap">
        select * from user
        where user_name = #{0} and dept_id = #{1}
    </select>

    #{}里面的数字代表你传入参数的顺序。

    这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

    @Param注解传参法

    public User selectUser(@Param("userName") String name, int @Param("deptId") deptId);
    
    <select id="selectUser" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>

    #{}里面的名称对应的是注解@Param括号里面修饰的名称。

    这种方法在参数不多的情况还是比较直观的,推荐使用。

    Map传参法

    public User selectUser(Map<String, Object> params);
    
    <select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>

    #{}里面的名称对应的是Map里面的key名称。

    这种方法适合传递多个参数,且参数易变能灵活传递的情况。

    PS:
    MyBatis传递map参数时,如果传递参数中没有对应的key值,在执行sql语句时默认取的是null

    例如:map中没有put “name”这个key,在sql中使用#{name}时,默认赋值null

    Java Bean传参法

    public User selectUser(User params);
    
    <select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>

    #{}里面的名称对应的是User类里面的成员属性。

    这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。

  • 相关阅读:
    RTMP命令亲自测试记录
    如何在 i5 上实现 20 倍的 Python 运行速度?
    百倍加速!Python量化策略的算法性能提升指南
    谷歌推出 Python 性能加速方案
    用Cython加速Python到“起飞”
    Python GPU加速
    金融数学太复杂?看完这10部电影会不会轻松点!
    金融数学攻略+书单
    耳朵如何保养
    DataOps Reading Notes
  • 原文地址:https://www.cnblogs.com/www-tty-com/p/14138813.html
Copyright © 2011-2022 走看看