使用hibernate作为持久工具,一个部门下面有多个员工,要在新建部门时,同时将新增的员工一起插入表中。
mysql建表:
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dname` varchar(45) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ename` varchar(45) COLLATE utf8_bin DEFAULT NULL,
`phone` varchar(45) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
)
/**
* 部门:与员工一对多关系
*
*/
@Entity
@Table(name="department")
public class Department {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(length=20)
private String dname; //部门名称
@OneToMany
private List<Employee> employeeList = new ArrayList<>(); //员工集合
// get/set方法
/**
* 员工:与部门多对一关系
*
*/
@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id; //ID
@Column(length=20)
private String ename; //员工姓名
@Column(length=20)
private String phone; //电话
@ManyToOne
private Department department; //所属部门
//get/set方法
}
//使用
Department d = new Department();
d.setDname("soft");
Employee e1 = new Employee();
e1.setEName("liao");
e1.setPhone("110")
Employee e2 = new Employee();
e2.setEName("liao");
e2.setPhone("110")
List<Employee> list = new ArrayList<>();
list.add(e1);
list.add(e2);
d.setEmployeeList(list);
网友评论