MyBatis04Map传值和模糊查询

导读:本篇文章讲解 MyBatis04Map传值和模糊查询,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1、Map 传值

  • Map 传递参数,直接在 sql 中取出 key 即可
  • parameterType=“map”
User selectUserByMap(Map<String,Integer> map);
<select id="selectUserByMap" parameterType="map" resultType="com.study.pojo.User">
    select * from tb_user where id = #{userId}
</select>
@Test
public void test03(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Integer> map = new HashMap<>();
    map.put("userId",1);
    User user = mapper.selectUserByMap(map);
    System.out.println(user);
    sqlSession.close();
}

2、mybatis中LIKE模糊查询的几种写法以及注意点

  • 方式一:使用${…}
List<User> selectUserLikeName(String name);
<select id="selectUserLikeName" parameterType="string" resultType="com.study.pojo.User">
    select * from tb_user where name like '%${name,jdbcType=VARCHAR}%'
</select>
@Test
public void test04(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = mapper.selectUserLikeName("李");
    users.forEach(System.out::println);
    sqlSession.close();
}

弊端:使用${…} 会引起 sql 注入问题,应尽量避免使用

  • 方式二:使用#{…}

接口和测试类不变,就改下xml文件

<select id="selectUserLikeName" parameterType="string" resultType="com.study.pojo.User">
    select * from tb_user where name like "%"#{name,jdbcType=VARCHAR}"%"
</select>

注意:因为#{…}解析成sql语句时候,会在变量外侧自动加单引号’ ‘,所以这里 % 需要使用双引号” “,不能使用单引号 ’ ‘,不然会查不到任何结果。

  • 方式三:使用CONCAT()函数连接参数形式

接口和测试类不变,就改下xml文件

<select id="selectUserLikeName" parameterType="string" resultType="com.study.pojo.User">
    select * from tb_user where name like concat('%',#{name,jdbcType=VARCHAR},'%')
</select>

3、mybatis中的#{}和${}区别

  • #{} 将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号;${} 将传入的数据直接显示生成在sql中
  • #{} 可以防止sql注入,${} 不可以防止sql注入
  • ${} 方式一般用于传入数据库对象,例如传入表名、列名;一般能用#{} 的就别用 ${}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/3087.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!