Mybatis框架-联表查询显示问题解决
需求:查询结果要求显示用户名,用户密码,用户的角色
因为在用户表中只有用户角色码值,没有对应的名称,角色名称是在码表smbms_role表中,这时我们就需要联表查询了。
这里需要在User实体类中添加一个字段-userRoleName并添加相应的set get方法
User.java
UserMapper.xml 注意:据库中的字段名和User实体类中的属性名是不一致的,必须进行手动映射
1 <!--查询结果要显示用户名,密码和用户的角色名称,需要连表查询 2 注意:roleName最后运行程序的结果是null 3 原因是:数据库中的字段名和User实体类中的属性名是不一致的,必须进行手动映射 r.roleName as userRoleName--> 4 <select id="getUserListByUserName4" parameterType="map" resultType="User" > 5 select a.*,r.roleName as userRoleName from smbms_user a,smbms_role r 6 where username like CONCAT ('%',#{userName1},'%') 7 and userRole = #{userRole1} and a.userRole=r.id 8 </select>
UserMapper.java
编写对应的测试方法:
1 @Test 2 public void test8() { 3 Map<String, String> map = new HashMap<String, String>(); 4 map.put("userName1", "赵"); 5 map.put("userRole1", "3"); 6 7 SqlSession sqlSession = null; 8 java.util.List<User> userList2 = new ArrayList<User>(); 9 try { 10 sqlSession = MyBatisUtil.createSqlSession(); 11 //使用mapper映射的方式实现 12 //userList2 = sqlSession.selectList("cn.smbms.dao.user.UserMapper.getUserListByUserName",userNameString); 13 //调用mapper接口的方式实现 14 userList2 = sqlSession.getMapper(UserMapper.class).getUserListByUserName4(map); 15 int size = userList2.size(); 16 mlogger.info("获取到的记录数是:" + size); 17 18 } catch (Exception e) { 19 // TODO: handle exception 20 } finally { 21 // 最后一定要注意:关闭会话 22 MyBatisUtil.closeSqlSession(sqlSession); 23 24 } 25 for (User user2 : userList2) { 26 mlogger.info("用户名:" + user2.getUserName() + ",密码:" + user2.getUserPassword()+",用户角色:"+user2.getUserRoleName()); 27 } 28 29 }
运行结果:
1 [DEBUG] 2019-11-02 19:59:50,022 cn.smbms.dao.user.UserMapper.getUserListByUserName4 - ==> Preparing: select a.*,r.roleName as userRoleName from smbms_user a,smbms_role r where username like CONCAT ('%',?,'%') and userRole = ? and a.userRole=r.id 2 [DEBUG] 2019-11-02 19:59:50,157 cn.smbms.dao.user.UserMapper.getUserListByUserName4 - ==> Parameters: 赵(String), 3(String) 3 [INFO] 2019-11-02 19:59:50,260 cn.smbms.dao.test.UserMapperTest - 获取到的记录数是:1 4 [DEBUG] 2019-11-02 19:59:50,260 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@ed0220c] 5 [DEBUG] 2019-11-02 19:59:50,261 org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@ed0220c] 6 [DEBUG] 2019-11-02 19:59:50,262 org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 248521228 to pool. 7 [INFO] 2019-11-02 19:59:50,262 cn.smbms.dao.test.UserMapperTest - 用户名:赵燕,密码:0000000,用户角色:普通员工