Mybatis multi-table query, one-to-one query

One to one

Precondition

When will one to one be used?

  1. Assuming there are two tables, one user table and one account table, a user can only have one account, and the user information and account information are all placed in one table, which seems very redundant. So we separate two tables.
  2. Suppose a game requires login authentication. User name and password can be listed in a separate table. Because only the user name and password are queried when logging in, a single table is the best solution, so that the query speed is fast and the user password The table should also be associated with the user information table.

Two options for one-to-one design

  1. Primary key sharing (pk+fk)
  2. Foreign key unique (fk+unique)

One to one query

There are two ways of one-to-one query
1. Create a subclass (not commonly used)
2. Have entity references from a table (commonly used)

Preparation environment
Now there are two tables, a user name (slave table), and an account table (master table)

  1. The slave table entity class should contain a package object reference for the master table entity
public class Account {
    
    
	private Integer id;
	private Integer uid;
	private Double money;
	//从表实体类中应该有一个主表的对象
	private User user;
	//提供getset方法 该重写的方法重写了
}
  1. Prepared SQL statement
select
	a.*,u.id,u.name,u.password
from
	account a
join
	user u
on
	a.uid = u.id

  1. Because there is an object of the main table in the Account (sub-table) table, then there is no way to encapsulate the User when the query result is encapsulated. It needs to be set like this (write resultMap in the mapping file)
<!--定义一个能封装account和user的resultMap-->
<resultMap id="accountUserMap" type="Account">
	<!--定义主键字段-->
	<id property="id" column="id"></id>
	<!--定义非主键字段-->
	<result property="uid" column="uid"></result>
	<result property="money" column="money"></result>
	
	<!--一对一的关系映射:配置user的内容-->
	<!--property:该实体类中的哪个对应关系的主表属性-->
	<!--column:通过哪一个 字段进行获取的-->
	<!--javaType:最后的结果封装到哪个类  正常写法是com.xxx.xx 用了TypeAlia..所以直接类名-->
	<association property="user" column="uid" javaType="User">
		<!--在里面写User的属性和数据库对应起来-->
		<id property="id" column="id"></id>
		<result property="name" column="name"></result>
		<result property="password" column="password"></result>
	</association>
</resultMap>

  1. Just write the sql statement as it is (write the id name from resultMap here)
<select id="findAll" resultMap="accountUserMap">
	select
		a.*,u.id,u.name,u.password
	from
		account a
	join
		user u
	on
		a.uid = u.id
</select>

This can be queried


Next update: Multi-table query, one-to-many query

Guess you like

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