閱讀974 返回首頁    go 技術社區[雲棲]


第十章 基於Annotation的關係映射 多對一與一對多

如果下麵部分內容有不明白的可以查找:

基於Annotation的關係映射 前期準備:https://blog.csdn.net/p_3er/article/details/9061911

基於xml的多對一:https://blog.csdn.net/p_3er/article/details/9036759

基於xml的一對多:https://blog.csdn.net/p_3er/article/details/9036921


本文是把多對一與一對多結合起來了,形成一個雙向的映射。如果隻想要單向的話,把別外一邊的注解去掉就是了。


Department:
@Entity
@Table(name = "department", catalog = "hibernate")
public class Department implements java.io.Serializable {
	private Integer id;
	private String name;
	private Set<Employee> employees = new HashSet<Employee>(0);

	public Department() {
	}

	public Department(String name, Set<Employee> employees) {
		this.name = name;
		this.employees = employees;
	}

	@Id
	@GeneratedValue
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name = "name", nullable = false, length = 45)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "department")
/*
一對多。
department和employee的一對多關係中,當指定department中的mappedBy後,關係隻能被employee來主動維護.也就是employee級聯的處理department. 
         之前的映射文件:
         <set name="employees" inverse="false" cascade="all">
			<key column="department_id"></key>
			<one-to-many />
		</set>

*/
	public Set<Employee> getEmployees() {
		return this.employees;
	}

	public void setEmployees(Set<Employee> employees) {
		this.employees = employees;
	}
}

Employee:
@Entity
@Table(name = "employee", catalog = "hibernate")
public class Employee implements java.io.Serializable {
	private Integer id;
	private Department department;
	private String name;
	public Employee() {
	}

	@Id
	@GeneratedValue
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "department_id")
/*
	多對一。
     <many-to-one name="department" column="department_id"></many-to-one>
*/
	public Department getDepartment() {
		return this.department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	@Column(name = "name", nullable = false, length = 45)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}
}




最後更新:2017-04-03 18:52:11

  上一篇:go 第十章 基於Annotation的關係映射 多對多
  下一篇:go 第十章 基於Annotation的關係映射 一對一