mybatis multi-table joint query, one-to-many

One to many

The essential

The foreign key of the account table refers to the primary key of the user table, so the account table is the slave table, and the user table is the master table

One-to-many relationship mapping: the main table entity should contain a collection of references from the table entity


premise:

  • Two tables: user table user, account table account
  • There is a foreign key in the account table that references the primary key of the user table
  • The toString of the entity class of the user table and the entity class of the account table must be rewritten (otherwise it will not be visible when querying)

achieve

  1. Define a method in UserDao
public interface UserDao{
    
    
	//查询所有用户和
	List<User> findAll();
}
  1. Properties in the User entity class
public User{
    
    
	private Integer id;
	private String name;
	private String password;
	//一对多的关系映射,主表实体中有从表是实体的集合引用
	private List<Account> accounts;
	//重写toString 
	//get set方法
}
  1. SQL statements prepared in advance
select
	u.*,a.id as aid ,a.uid,a.money
from
	user u
left join
	account a
on
	u.id = a.uid
  1. Write the mapping relationship in the mapping file
<!--定义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. Write the test class
    This will query the results.

Next article update: mybatis multi-table query, many-to-many

Guess you like

Origin blog.csdn.net/m0_46409345/article/details/108707126