第十章 基于Annotation的关系映射 多对一与一对多

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

基于Annotation的关系映射 前期准备:http://blog.csdn.net/p_3er/article/details/9061911

基于xml的多对一:http://blog.csdn.net/p_3er/article/details/9036759

基于xml的一对多:http://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 class="cn.framelife.hibernate.entity.Employee"/>
		</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;
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值