table of Contents
1. One-to-one relationship
One-to-one relationship in the database-primary key association and foreign key key
such as person table and ID card table
1. Primary key association
create table person (
pid int primary key auto_increment,
pname varchar(40) not null,
pgender varchar(10) not null
)
create table card (
cid int not null, -- 引用person表的主键(由程序控制)
cnumber varchar(18) not null
)
2. The foreign key association
person table remains unchanged, and the foreign key column of the card table is added
create table card (
cid int not null primary key auto_increment,
cnumber varchar(18) not null,
pid int,
foreign key(pid) references person(pid)) -- person的主键(应该程序控制)
)
2. One-to-one foreign key association query configuration
- sql Take user table and order table as examples, order and user one-to-one
create table `users1` (
`userId` int (11),
`userName` varchar (60),
`userPassword` varchar (120),
`birthday` bigint (255)
);
create table `orders` (
`order_id` int (11),
`order_time` datetime ,
`order_money` Decimal (11),
`uid` int (11)
);
package cn.bitqian.entity;
import java.sql.Timestamp;
/**
* 用户订单表 一对一
* 一个订单对应一个用户...
* @author echo lovely
* @date 2020/9/13 10:26
*/
public class Order {
private Integer orderId;
private Timestamp orderTime;
private Double orderMoney;
// 当前订单对应的用户.. 面向对象表示
private User user;
// constructor.. set/get toString..
}
<?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="cn.bitqian.dao.OrderMapper">
<!-- 给Order封装数据 -->
<resultMap id="orderMap" type="Order">
<id property="orderId" column="order_id"/>
<result property="orderTime" column="order_time"/>
<result property="orderMoney" column="order_money"/>
<!-- 封装order里面的user -->
<!--<result property="user.userId" column="userid"/>
<result property="user.userName" column="username"/>
<result property="user.userPassword" column="userpassword"/>
<result property="user.birthday" column="birthday"/>-->
<!-- user属性 User类型-->
<association property="user" javaType="User">
<id property="userId" column="userid"/>
<result property="userName" column="username" />
<result property="userPassword" column="userpassword" />
<result property="birthday" column="birthday" />
</association>
</resultMap>
<!-- 返回的是order -->
<select id="queryAllOrder" resultMap="orderMap">
SELECT *, u.`userId` AS userid FROM orders o LEFT JOIN users1 u
ON o.`uid` = u.`userId`
</select>
</mapper>