MyBatis专栏 - 关联查询之一对一
一对一
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