[Crazy God MyBatis Notes] map as a parameter transfer type for addition, deletion, modification, and fuzzy query

The parameters in the interface are passed into the map;

The incoming parameter of the implementation class is the name of the key of the map, which can be customized;

Example: Get user by ID

interface:

//根据ID获取用户
   User getUserById2(Map<String,Object>map);

Interface implementation class:

   <select id="getUserById2" parameterType="map" 
                             resultType="com.kuang.pojo.User">
    select * from mybatis.user where id=#{userId};//userId是自定义的键,用来作为id的参数
  </select>

Test class:

   @Test
    public void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",3);
        User userById2 = mapper.getUserById2(map);
        System.out.println(userById2);
        sqlSession.commit();
        sqlSession.close();
    }

Map passes parameters and directly takes out the key in sql

The object passes parameters and directly retrieves the properties of the object in sql

There is only one basic type parameter, no need to write parameterType

Example: add user

interface:

int addUser2(Map<String,Object> map);

 Implementation class:

    <insert id="addUser2" parameterType="map">
    insert into mybatis.user (id,name,pwd) values(#{userId},#{userName},#{passWord});
    </insert>

//userId,userName,passWord为map自定义键

Test class:

   @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",5);
        map.put("userName","saf");
        map.put("passWord","09090");
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }

Fuzzy query:

 

Example: Get users with passwords ending in 4

interface:

 //模糊查询
    List<User>getUserLike(String value);

Implementation class:

  <select id="getUserLike" resultType="com.kuang.pojo.User">
        select * from mybatis.user where pwd like #{value}
    </select>

In order to prevent SQL injection, like is written in the form of a parameter. When the java code is executed, pass the wildcard %

Test class:

    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userLike = mapper.getUserLike("%4");
        for (User user : userLike) {
            System.out.println(user);
        }
        sqlSession.close();
    }

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/124350333