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

Posted 积水成渊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis学习第2节 -- 模糊查询之#和$的区别相关的知识,希望对你有一定的参考价值。

先说结论, #是占位符,而$的行为是字符串拼接, 在参数是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节 -- 模糊查询之#和$的区别的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis学习第20节 -- 嵌套结果

MyBatis学习10高级映射之多对多查询

MyBatis学习10高级映射之多对多查询

Mybatis学习第19节 -- 嵌套查询一对多的配置

Mybatis学习第25节 -- 懒加载 积极与不积极

Mybatis学习第6节 -- 修改功能和修改部分字段