需求:查询账户信息,关联查询用户信息。
分析:因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。
表结构如下:
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//加入User类的对象作为Account类的一个属性
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}
}
public interface AccountMapper {
Account getAccountById(Integer id);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.fpl1116.mapper.AccountMapper">
<resultMap id="getAccountByIdResultMap" type="account">
<id column="aid" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
<!--
一对一查询使用association标签
property="user":Account的属性名
javaType="user":等价于resultType
-->
<association property="user" javaType="user">
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
<result column="address" property="address"></result>
</association>
</resultMap>
<select id="getAccountById" parameterType="int" resultMap="getAccountByIdResultMap">
SELECT a.id aid, a.money money, a.uid uid, u.* FROM account a LEFT JOIN USER u ON a.uid = u.id WHERE a.id=1
</select>
</mapper>
@Test
public void testGetAccountById() throws IOException {
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
Account account = accountMapper.getAccountById(1);
System.out.println(account);
}