MyBatis使用Map和模糊查询

2022-07-19 14:29:12

MyBatis使用Map和模糊查询

当我们的实体类、或者数据库里的表、字段或者参数很多,这个时候考虑使用map

一、使用map传参插入数据

1.编写Dao接口/Mapper层 使用Map做参数

//Dao接口/Mapper层 使用Map传参intaddUser2(Map<String,Object> map);

2.编写Mapper.xml中的sql语句

<!--    传递map的key--><insertid="addUser2"parameterType="map">
        insert into firend_mq.users (id,username,password) value (#{userid},#{name},#{pwd})</insert>

3.编写测试类

//使用map传参添加插入@TestpublicvoidaddUser2(){

        SqlSession sqlSession= Mybatisutil.getSqlSession();
        UserDao mapper= sqlSession.getMapper(UserDao.class);
        Map<String, Object> map=newHashMap<String, Object>();

        map.put("userid",4);
        map.put("name","好人");
        map.put("pwd",1111111);

        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();}

在这里插入图片描述
使用Map传参也可以批量插入数据
MyBatis 批量插入/修改/删除数据(MySql)

二、使用map修改数据

当我们的实体类、或者数据库里的表、字段或者参数很多的时候,使用一般的实体类传参,就需要将所有的字段全部写入,显然太过于繁琐,这时候使用map传入你需要更改的字段就行

代码大致相似就不放代码了。。。

三、模糊查询

1.方式一:java代码执行的时候,传递通配符% %

List<User> likelist= mapper.getUserlike("%毛%");

2.方式二:在Mapper.xml中的sql拼接中使用通配符

select * from firend_mq.users where username like "%"#{value}"%"

实现结果:
在这里插入图片描述

总结:

  • Map传递参数,直接写sql语句中取出即可 {parameterType=“map”}
    优点可以在取参数#{value}的时候可以DIY,直接使用自己传入的key值
  • 对象传递参数,直接在sql中取对象的属性即可 {parameterType=“Object”}
    但是必须和实体类名字一致
  • 只有一个基本类型参数的情况下,可以直接在sql中取到
  • 多个参数用Map,或者注解
  • 作者:浪漫主义码农
  • 原文链接:https://blog.csdn.net/Mq_sir/article/details/116259490
    更新时间:2022-07-19 14:29:12