码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis 实用篇(三)参数处理

时间:2018-10-05 22:38:29      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:使用   mybatis   一个   工作   interface   拼接   @param   取出   数据库   

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}


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

Mybatis 实用篇(三)参数处理

标签:使用   mybatis   一个   工作   interface   拼接   @param   取出   数据库   

原文地址:https://www.cnblogs.com/binarylei/p/9746134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!