MyBatis关联查询(二、一对多查询)
需求:查询所有用户信息及用户关联的账户信息。
分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,此时左外连接查询比较合适。
基础项目搭建参考第一个mybatis项目的创建和读取数据库信息
MyBatis关联查询(一、一对一查询)
在上面项目的基础上先编写user表的pojo文件
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//多方
private List<Account> accountList;
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public List<Account> getAccountList() {
return accountList;
}
public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
编写UserMapper.java代码
public interface UserMapper {
User getUserById(Integer id);
}
在UserMapper.xml中编写下列代码
<resultMap id="getUserByIdResult" type="cn.fpl1116.pojo.User">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!--一堆多使用collection标签指定数据的封装规则-->
<collection property="accountList" ofType="cn.fpl1116.pojo.Account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="getUserByIdResult">
SELECT u.*, a.id aid, a.uid uid, a.money money FROM user u LEFT JOIN account a ON u.id=a.uid WHERE u.id=#{id}
</select>
编写测试方法
@Test
public void testGetUserById(){
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(41);
System.out.println(user);
}