Mybatis获取参数值的各种情况

public interface SelectMapper {

    //根据ID查询用户信息
    User getUserById(@Param("id") Integer id);

    //查询所有用户信息
    List getAllUser();

    //查询用户信息的总记录数
    Integer getCount();

    //查询用户信息使用map
    Map getUserByIdToMap(@Param("id") Integer id);

    //查询指定年龄的人的信息
    String getNameByAge(@Param("age") Integer age);

    //查询所有用户信息 使用ListMap
    List> getAllUserToListMap();

    //查询所有用户信息使用Map
    @MapKey("id")
    Map getAllUserToMap();
}
  /*
     * @author h
     * @desc
     * Mybatis中获取参数值的两种方式:${},#{}
     * ${}本质是字符串拼接
     * #{}本质是占位符
     * Mybatis获取参数值的各种情况:
     * 1、mapper接口方法的参数
     * 2、mapper接口方法的参数有多个
     *  此时Mybatis会将参数放入一个Map集合中,以两种方式进行存储
     * 3、若mapper接口方法的参数有多个时,可以手动将这些参数放在map中存储
     * 4、mapper接口方法的参数是实体类类型的参数
     *  通过属性来访问即可
     * 5、命名参数(注解)
     */
    @Test
    public void getAllUser(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
        List users = mapper.getAllUser();
        for (Object o: users
             ) {
            System.out.println(o);
        }
    }
    @Test
    public void getUserByUsername(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
        User user = mapper.getUserByUsername("张三");
        System.out.println(user);
    }

    @Test
    public void checkLogin(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
        User user = mapper.checkLogin("张三","123456");
        System.out.println(user);
    }

    @Test
    public void checkLoginByMap(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
        Map map = new HashMap<>();
        map.put("username","张三");
        map.put("password","123456");
        User user = mapper.checkLoginByMap(map);
        System.out.println(user);
    }

    @Test
    public void insertUser(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
        int result = mapper.insertUser(new User(null,"李四","abc123",23,"男","[email protected]"));
        System.out.println(result);
    }

}



    
    

    
    

    
    

    
    

    
    
        insert into t_user values(null, #{username},#{password},#{age},#{sex},#{email})
    

注意最后一个案例 增加user的操作中

因为mybatis中底层是用Map来表示的,当操作的对象是一个实体类时,只需要用其属性值作为键即可得到对应的值。

常用的为@Param()

Mybatis获取参数值的各种情况_第1张图片

#{id} @Param中的键所对应的值

你可能感兴趣的:(java,eureka,开发语言)