1. 程式人生 > >Mybatis一對多中的SQL(查詢、刪除、更新、插入)及表的設計

Mybatis一對多中的SQL(查詢、刪除、更新、插入)及表的設計

1.1現實模型

一個Teacher有多個Student,一個Student有一個Teacher,通過Teacher來管理Student

1.2實體類

Teacher

public class Teacher
{
    private int id;
    private String name;
    private Set<Student> stus=new HashSet<Student>();
}

Student

public class Student
{
    private int id;
    private String name;
}

1.3表的設計

teacher

t_id t_name
14 劉繼兵

student

s_id s_name tea_id
7 鄧超元 14
8 餘輝 14

tea_id位student表的外來鍵

1.3.1建立表的SQL

create table teacher(t_id int primary key auto_increment,t_name char(20));
create table student(s_id int primary key auto_increment,s_name char
(20),tea_id int);

1.3.2新增外來鍵

alter table student add constraint t_s_const foreign key(tea_id) references teacher(t_id) on delete cascade on update cascade;

1.4SQL語句

1.4.1插入

插入單挑資料:insert into teacher(t_name) values(?);
插入多條資料:insert into student(s_name,tea_id) values ('xio',1),('dad',2
);

1.4.2刪除

delete from teacher where t_id=?;

1.4.3更新

update teacher set t_name='jhonson' where t_id=?;

1.4.4查詢

select teacher.*, student.s_id,student.s_name from teacher left outer join student on 
student.tea_id=teacher.t_id where teacher.t_id=?;