mybatis多表联合查询,一对多

一对多

关键

账户表的外键引用了用户表的主键,那么说账户表是从表,用户表是主表

一对多的关系映射:主表实体中应该包含从表实体的集合引用


前提:

  • 两张表:用户表user,账户表account
  • 账户表中有外键引用用户表的主键
  • 用户表实体类和账户表实体类的toString一定要重写(不然查询出来的时候看不出来)

实现

  1. 在UserDao中定义一个方法
public interface UserDao{
    
    
	//查询所有用户和
	List<User> findAll();
}
  1. User实体类中的属性
public User{
    
    
	private Integer id;
	private String name;
	private String password;
	//一对多的关系映射,主表实体中有从表是实体的集合引用
	private List<Account> accounts;
	//重写toString 
	//get set方法
}
  1. 提前准备好的SQL语句
select
	u.*,a.id as aid ,a.uid,a.money
from
	user u
left join
	account a
on
	u.id = a.uid
  1. 在映射文件中写映射关系
<!--定义User的resultMap 一对多查询-->
<!--id 随便起一个名字 type:类型仍然是一个User 配置了别名所以直接写类名-->
<resultMap id="UserAccountMap" type="User">
	<id property="id" column="id"></id>
	<result property="name" column="name"></result>
	<result property="password" column="password"></result>
	
	<!--配置user对象中accounts集合的映射-->
	<!--property:User对象的Account属性名-->
	<!--ofType:集合中元素的类型(用了别名 不然要写权限定类名)-->
	<!--一对多需要用 collection标签 -->
	<collection property="accounts" ofType="Account">
		<id property="id" column="aid"></id>
		<result property="uid" column="uid"></result>
		<result property="money" column="money"></result>
	</collection>
</resultMap>

为什么是column是aid 因为查询的有两个id 一个用户id 一个 账户id 为了区分在起了个别名
同时 sql语句也要写上  a.id as aid
  1. 编写测试类
    这样就查询出来结果了。

下一篇更新:mybatis多表查询,多对多

猜你喜欢

转载自blog.csdn.net/m0_46409345/article/details/108707126