需求:查询所有用户信息及用户关联的账户信息。
分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,我们想到了左外连接查询比较合适。
文章目录
一、一对多查询
(1)修改User 类,为其加入 账户信息
@Data
public class User implements Serializable{
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
/**
* 一对多关系映射:主表实体应该包含从表实体的集合引用
*/
private List<Account> accounts;
}
(2)对应的UserDao 接口的查询方法
public interface UserDao {
/**
* 查询所有操作
* @return
*/
List<User> findAll();
}
(3)相应的UserDao.xml 的编写
<mapper namespace="mybatis.dao.UserDao">
<!--提取重复的 SQL 语句-->
<sql id="defaultUser">
select * from user
</sql>
<!--定义封装account和user的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!-- 配置user对象中accounts集合的映射 -->
<collection property="accounts" ofType="account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
<!--查询所有用户-->
<!--id 表示方法名称,resultType 表示要封装到哪里去-->
<select id="findAll" resultMap="userAccountMap">
select * from user u left outer join account a on u.id = a.uid;
</select>
</mapper>
这里注意collection
是用于建立一对多中集合属性的对应关系,ofType
用于指定集合元素的数据类型
collection:用于建立一对多中集合属性的对应关系
property="accounts":对应的实体类中的属性
ofType="account":指定关联查询的结果集中的对象类型。此处可以使用别名,也可以使用全限定名。
二、分布实现一对多查询
背景表同:分布实现一对一查询
/**
* 通过分步查询查询部门以及部门所对应的学生信息
* 分步查询第一步:通过cid查询班级
*/
StuClass getClassAndStuByStepOne(@Param("cid") Integer cid);
<resultMap id="classAndStuClassByStepResultMap" type="stuClass">
<id property="cid" column="cid"></id>
<result property="className" column="cname"></result>
<collection property="students"
select="com.atguigu.mybatis.mapper.StuMapper.getClassAndStuByStepTwo"
column="cid"
fetchType="eager"></collection>
</resultMap>
<!--StuClass getClassAndStuByStepOne(@Param("cid") Integer cid);-->
<select id="getClassAndStuByStepOne" resultMap="classAndStuClassByStepResultMap">
select * from class where cid = #{cid}
</select>
/**
* 通过分步查询查询部门以及部门所对应的学生信息
* 分步查询第二步:查询学生信息
*/
Student getClassAndStuByStepTwo(@Param("cid") Integer cid);
<!--Student getStuAndClassByStepOne(@Param("sid") Integer sid);-->
<select id="getStuAndClassByStepOne" resultMap="stuAndClassByStepResultMap">
select * from stu where sid = #{sid}
</select>
@Test
public void testGetClassAndStuByStep(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ClassMapper mapper = sqlSession.getMapper(ClassMapper.class);
StuClass students = mapper.getClassAndStuByStepOne(1);
System.out.println(students.getStudents());
// System.out.println(student.getAClass().getCid());
}