部门表
create table dept(
id int not null auto_increment, //部门的ID主键
name varchar(32), //部门名称
origid varchar(32) //部门编号
primary key (id)
)type=InnoDB DEFAULT CHARSET=utf8; 员工表 create table staff(
id int not null auto_increment, //员工ID
dept_id int, //部门ID
primary key (id),
)type=InnoDB DEFAULT CHARSET=utf8; 这里dept.id=staff.dept_id 在多对一关系中,即staff是主表,dept是从表,有问题请教
Staff staff=new Staff();
staff.setName("张三");
Dept dept=new Dept();
dept.setName("xxx");
//dept.setId(6);
staff.setDept(dept);
session.save(staff);
运行后插入了一条dept记录和一条staff记录
如果我把dept.setId(6);注释去掉,就直插入一条staff记录,书本上说这是因为指定了外键ID,就不会执行从表的插入操作。
这我就不明白了,如果dept表中ID=6的记录不存在,也不会在dept表中加入记录吗?为什么?
create table dept(
id int not null auto_increment, //部门的ID主键
name varchar(32), //部门名称
origid varchar(32) //部门编号
primary key (id)
)type=InnoDB DEFAULT CHARSET=utf8; 员工表 create table staff(
id int not null auto_increment, //员工ID
dept_id int, //部门ID
primary key (id),
)type=InnoDB DEFAULT CHARSET=utf8; 这里dept.id=staff.dept_id 在多对一关系中,即staff是主表,dept是从表,有问题请教
Staff staff=new Staff();
staff.setName("张三");
Dept dept=new Dept();
dept.setName("xxx");
//dept.setId(6);
staff.setDept(dept);
session.save(staff);
运行后插入了一条dept记录和一条staff记录
如果我把dept.setId(6);注释去掉,就直插入一条staff记录,书本上说这是因为指定了外键ID,就不会执行从表的插入操作。
这我就不明白了,如果dept表中ID=6的记录不存在,也不会在dept表中加入记录吗?为什么?
因为根据表的约束(这种约束同进也映射到 相应的对象关系中了),不指定dept.setId(6),就会当作新的dept对象.指定了就会查找数据库是否存在,再决定是插入还是更新