SSM根据用户名和用户角色, 模糊查询用户列表--封装到User对象和Map中

一、封装到User对象中

1-UserMapper.java

//需求:根据用户名和用户角色, 模糊查询用户列表--封装到实体类
//public List getUserListByUserNameAndUserRole(String userName,Integer userRole);
public List<User> getUserListByUserNameAndUserRole(User user);

2-UserMapper.xml

<!--需求:根据用户名和用户角色, 模糊查询用户列表:#{必须对象的属性名,能随便写}-->
<select id="getUserListByUserNameAndUserRole"  parameterType="User" resultType="User">
    SELECT *
    FROM smbms_user
    WHERE userName
    LIKE CONCAT('%',#{userName},'%')
    AND userRole=#{userRole}
</select>

3-测试类

@Test
    public void getUserListByUserNameAndUserRoleTest(){
        SqlSession sqlSession = MyBatisUtil.createSqlSession();

/*        String userName="赵";
        Integer userRole=2;*/
        User user = new User();
        user.setUserName("赵");
        user.setUserRole(2);

        List<User> userList = sqlSession.getMapper(UserMapper.class).getUserListByUserNameAndUserRole(user);

        for(User u:userList){
            logger.debug(u.getId()+"\t"+u.getUserName()+"\t"+u.getUserRole());
        }

        //提交事务
        sqlSession.commit();

        MyBatisUtil.closeSqlSession(sqlSession);
    }

二、封装到Map中

1-UserMapper.java

//需求:根据用户名和用户角色, 模糊查询用户列表--封装到map
public List<User> getUserListByUserNameAndUserRole_map(Map<String,Object> userMap);

2-UserMapper.xml

<!--需求:根据用户名和用户角色, 模糊查询用户列表:封装到map;#{写map的key值}-->
<select id="getUserListByUserNameAndUserRole_map" parameterType="map" resultType="User">
    select * from smbms_user
    where userName like CONCAT('%',#{yiyang},'%') and userRole=#{qianxi}
</select>

3-测试类

@Test
    public  void getUserListByUserNameAndUserRole_mapTest(){
        SqlSession sqlSession = MyBatisUtil.createSqlSession();

        Map<String,Object> userMap=new HashMap<>();

        userMap.put("yiyang","赵");
        userMap.put("qianxi","2");

        List<User> userList = sqlSession.getMapper(UserMapper.class).getUserListByUserNameAndUserRole_map(userMap);

        for(User u:userList){
            logger.debug(u.getId()+"\t"+u.getUserName()+"\t"+u.getUserRole());
        }

        //提交事务
        sqlSession.commit();

        MyBatisUtil.closeSqlSession(sqlSession);
    }

你可能感兴趣的:(SSM根据用户名和用户角色, 模糊查询用户列表--封装到User对象和Map中)