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}


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

  • 相关阅读:
    Sublime Text 3 Build 3143 可用License
    npm安装cnpm报错
    使用proxy来简单的实现一个观察者
    时间倒计时提醒
    JavaScript设计模式
    异步方法(promise版)出错自调用
    co模块源码学习笔记
    go new() 和 make() 的区别
    广度优先搜索算法
    并发和并行有什么区别?(转)
  • 原文地址:https://www.cnblogs.com/binarylei/p/9746134.html
Copyright © 2011-2022 走看看