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

Mybatis学习第2节 -- 模糊查询之#和$的区别

时间:2019-03-16 19:21:55      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:hone   img   map   ida   查询   需求   bat   string   错误   

先说结论, #是占位符,而$的行为是字符串拼接, 在参数是java的基本类型且只有一个参数的情况下,使用$时,只能用value作为参数传递
需求决定设计, 先在interface里面添加相应方法
public interface ShopMapper {

Shop getShopById(Integer id);
Shop getShopByIdAlias(Integer id);

Shop getShopByTitleContainDollar(String value);
Shop getShopByTitleContainSharp(String value);
然后编写mapper文件对应的查询语句
<select id="getShopByTitleContainSharp" resultMap="simpleResultMap" >
select * from tb_shop where `shop_name` LIKE #{value}
</select>

<select id="getShopByTitleContainDollar" resultMap="simpleResultMap" >
select * from tb_shop where `shop_name` LIKE "${value}"
</select>
在测试类中进行测试
@Test
public void testGetShopByTitleContainSharp() {
String template = "查询结果: %s";
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.printf(template, mapper.getShopByTitleContainSharp("%ab%"));
session.close();
}
@Test
public void testGetShopByTitleContainDollar() {
String template = "查询结果: %s";
SqlSession session = MyBatisUtil.getSqlSession();
ShopMapper mapper = session.getMapper(ShopMapper.class);
System.out.printf(template, mapper.getShopByTitleContainSharp("%黄人%"));
session.close();
}
 
$方式拼接字符串
==> Preparing: select * from tb_shop where `shop_name` LIKE ? 
==> Parameters: %黄人%(String)
<== Columns: shop_id, owner_id, area_id, shop_category_id, shop_name, shop_desc, shop_addr, phone, shop_img, priority, create_time, last_edit_time, enable_status, advice
<== Row: 28, 1, 2, 22, 小黄人主题奶茶店, 不接受预订,请直接来店里进行消费, 位于东苑2号, 13810524086, /upload/images/item/shop/28/2017092601041469991.png, 50, 2017-09-26 01:04:13, 2017-09-26 01:04:13, 1, null
<== Total: 1

 

#方式特点
==> Preparing: select * from tb_shop where `shop_name` LIKE ? 
==> Parameters: %黄人%(String)
<== Columns: shop_id, owner_id, area_id, shop_category_id, shop_name, shop_desc, shop_addr, phone, shop_img, priority, create_time, last_edit_time, enable_status, advice
<== Row: 28, 1, 2, 22, 小黄人主题奶茶店, 不接受预订,请直接来店里进行消费, 位于东苑2号, 13810524086, /upload/images/item/shop/28/2017092601041469991.png, 50, 2017-09-26 01:04:13, 2017-09-26 01:04:13, 1, null
<== Total: 1
 

如果面对中文内容有错误谨记在连接url里面设置参数

jdbc:mysql://localhost:3306/oto?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

Mybatis学习第2节 -- 模糊查询之#和$的区别

标签:hone   img   map   ida   查询   需求   bat   string   错误   

原文地址:https://www.cnblogs.com/litran/p/10543447.html

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