先说结论, #是占位符,而$的行为是字符串拼接, 在参数是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> |
在测试类中进行测试
@Testpublic void testGetShopByTitleContainSharp() { String template = "查询结果: %s"; SqlSession session = MyBatisUtil.getSqlSession(); ShopMapper mapper = session.getMapper(ShopMapper.class); System.out.printf(template, mapper.getShopByTitleContainSharp("%ab%")); session.close();}@Testpublic 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 |
原文地址:https://www.cnblogs.com/litran/p/10543447.html
时间: 2024-10-10 16:39:11