mybatis中三表联查(分步查询)

  • Post author:
  • Post category:其他



实体类:

public class Usr {

  private String no;
  private String pwd;
  private Long positionId;
    // 学生对象
  private Student student;
    // 角色
  private List<Role> roles;

}


public class Student {

  private String stuNo;
  private String stuName;

}

public class Role {

  private long roleId;
  private String role;
  private long positionId;

}


mapper:

public interface UsrMapper {

    List<Usr> queryAllElements(String no);
    
}
// mapper类中的方法             返回map集合
 <select id="queryAllElements" resultMap="usrs" parameterType="string">
        select * from usr where `no`=#{no}
    </select>
  
            //设置map集合      类型        自动匹配
    <resultMap id="usrs" type="usr" autoMapping="true">
                //防止匹配不上手动设置匹配
            <result property="no" column="no"></result>
            <result property="positionId" column="position_id"></result>

                                                                       //queryAllElements
  //返回值是单个对象  对应实体类里的对象名      选择需要调用的方法名       选择列 (上面搜索表格对应列)
            <association property="student" select="selectStuByStuNo" column="no"></association>

                                                                                   //queryAllElements
  //返回值是个集合    对应实体类里的对象名          选择需要调用的方法名            选择列 (上面搜索表格对应列)
            <collection property="roles" ofType="role" select="selectRoleByPositionId" column="position_id"></collection>

    </resultMap>
            
            //查询学生信息
    <select id="selectStuByStuNo" resultType="student" parameterType="string">
        select * from student where stu_no = #{stuNo}
    </select>

            //查询角色
    <select id="selectRoleByPositionId" resultType="role" parameterType="int">
        select * from role where position_id = #{positionId}
    </select>

最后去测试类测试一下就OK了

@Test
    public void test01(){
        SqlSession sqlSession = factory.openSession();
        UsrMapper mapper = sqlSession.getMapper(UsrMapper.class);
        List<Usr> usrs = mapper.queryAllElements("HFYY1831234");
        usrs.forEach(usr -> System.out.println("usr = " + usr));
    }
//输出结果
usr = Usr(no=HFYY1831234, pwd=e10adc3949ba59abbe56e057f20f883e, positionId=1, student=Student(stuNo=HFYY1831234, stuName=张三), roles=[Role(roleId=1, role=学生, positionId=1)])



版权声明:本文为TanWuYou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。