使用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`)
)
/**
* 部門:與員工一對多關(guān)系
*
*/
@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方法
/**
* 員工:與部門多對一關(guān)系
*
*/
@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);