一(多)对一
1.需求
本次案例以简单的用户和账户的模型来分析 Mybatis 多表关系。用户为 User 表,账户为Account 表。一个用户(User)可以有多个账户(Account),但是一个账户(Account)只能属于一个用户(User)。
查询所有账户信息, 关联查询账户的用户名和地址。
因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。
- 数据库的准备
CREATE TABLE t_account(
aid INT PRIMARY KEY auto_increment,
money DOUBLE,
uid INT
);
ALTER TABLE t_account ADD FOREIGN KEY(uid) REFERENCES t_user(uid);
INSERT INTO `t_account` VALUES (null, '1000', '1');
INSERT INTO `t_account` VALUES (null, '2000', '1');
INSERT INTO `t_account` VALUES (null, '1000', '2');
INSERT INTO `t_account` VALUES (null, '2000', '2');
INSERT INTO `t_account` VALUES (null, '800', '3');
2.分析
- 查询语句
select * from t_user u,t_account a where a.uid=u.uid and u.uid=#{uid}
3.实现
-
修改Account.java
在 Account 类中加入 User类的对象作为 Account 类的一个属性。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account implements Serializable {
private Integer aid;
private Double money;
private Integer uid;
/**
* 表示Account和User的一对一关系
*/
private User user;
}
- AccountDao.java
public interface AccountDao {
/**
* 根据账户的aid查询出账户信息,并且连接t_user表获取该账户的用户信息
* @param aid
* @return
*/
Account findAccountUserByAid(int aid);
}
- AccountDao.xml
<?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="com.itheima.dao.AccountDao">
<!--
使用resultMap标签自定义映射规则
-->
<resultMap id="accountUserMap" type="Account">
<id column="aid" property="aid"></id>
<result column="money" property="money"></result>
<result column="uid" property="uid"></result>
<!--
要进行一对一的映射配置
property表示要映射的pojo的属性名
javaType表示要进行映射的POJO的属性的类型
-->
<association property="user" javaType="User">
<result column="uid" property="uid"></result>
<result column="username" property="username"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
<result column="address" property="address"></result>
</association>
</resultMap>
<select id="findAccountUserByAid" parameterType="int" resultMap="accountUserMap">
select * from t_account a,t_user u where a.uid=u.uid and a.aid=#{aid}
</select>
</mapper>