zoukankan      html  css  js  c++  java
  • Mybatis 实用篇(三)参数处理

    Mybatis 实用篇(三)参数处理

    sql 语句中的参数 parameterType 可以省略不写。

    一、参数封装

    1.1 单个参数处理

    public interface UserMapper {
        User getUser(int id);
    }
    

    sql 中 #{} 的值可以随意,mybatis 不做任何处理,eg:

    <select id="getUser" parameterType="int" resultType="User">
        select * from user where id=#{xxx};
    </select>
    

    1.2 多个参数处理

    多个参数 mybatis 封装成 Map,默认参数的 key 为 param1, param2...,也可以使用 @Param("id") 指定 key 的值

    User getUser(@Param("id") int id, String name);
    

    sql 可以有如下写法:

    <select id="getUser" resultType="User">
        <!--select * from user where id=#{0} and name=#{1};-->
        <!--select * from user where id=#{param1} and name=#{param2};-->
        <!--select * from user where id=#{0} and name=#{param2};-->
        select * from user where id=#{id} and name=#{param2};
    </select>
    

    1.3 Java Bean

    User getUser(User user);
    

    sql 可以有如下写法:

    <select id="getUser" resultType="User">
        select * from user where id=#{id} and name=#{name};
    </select>
    

    1.4 Map

    User getUser(User user);
    

    sql 可以有如下写法:

    <select id="getUser" resultType="User">
        select * from user where id=#{id} and name=#{name};
    </select>
    

    思考:

    User getUser(@Param("id") int id, String name);
    id ==> #{id/param1/0}   name ==> #{param2/1}
    
    User getUser(int id, @Param("user") User user);
    id ==> #{id/param1/0}   name ==> #{param2.name/user.name}
    
    # Collection ==> list, Array ==> array. eg: 取出 list 中的第一个值
    User getUser(List<User> users);
    id ==> #{list[0]}
    

    二、#{} 和 ${} 区别

    #{} 预编译,而 ${} 仅进行字符串拼接。

    实际工作中,尽量使用 #{} ,特殊场合需要使用 ${},如:

    select * from ${tablename}
    

    三、#{} 参数

    mybatis 值为 null 时默认对应数据库中的 TYPES.OHTER,可以修改全局的配置:

    • {email, javaType=NULL}


    每天用心记录一点点。内容也许不重要,但习惯很重要!

  • 相关阅读:
    git 教程
    darknet_ros 踩坑与解决办法
    相机与手臂的校准
    相机的内参外参标定
    VNC windous->linux
    12306 官网硬卧下铺的选择
    /usr/bin/ld: cannot find -lopencv_dep_cudart
    在Windows上安装GPU版Tensorflow
    机器学习基础
    [设计模式]行为型设计模式
  • 原文地址:https://www.cnblogs.com/binarylei/p/9746134.html
Copyright © 2011-2022 走看看