第九章 关系映射 多对一关联映射

如:departmentemployee

employee中有一个department_id的外键

Department:

public class Department implements Serializable {
	private Integer id;
	private String name;

	public Department() {
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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


Employee:

public class Employee implements Serializable {
	private Integer id;
	private String name;
	private Department department;

	public Department getDepartment() {
		return department;
	}

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

	public Employee() {
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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


Department.hbm.xml:(与普通的映射文件一样)

<hibernate-mapping>
	<class name="cn.framelife.hibernate.entity.Department" table="department"
		catalog="hibernate">
		<id name="id" type="java.lang.Integer">
			<column name="id" />
		</id>
		<property name="name" type="java.lang.String">
			<column name="name" length="45" not-null="true" />
		</property>	
	</class>
</hibernate-mapping>

Employee.hbm.xml:

<hibernate-mapping>
	<class name="cn.framelife.hibernate.entity.Employee" table="employee"
		catalog="hibernate">
		<id name="id" type="java.lang.Integer">
			<column name="id" />
			<generator class="native"></generator>
		</id>
		<property name="name" type="java.lang.String">
			<column name="name" length="45" not-null="true" />
		</property>	
		<many-to-one name="department" column="department_id"></many-to-one>
	</class>
</hibernate-mapping>

增加:

transaction = session.beginTransaction();
			Department department = new Department();
			department.setName("bb");
			session.save(department);
			Employee employee = new Employee();
			employee.setDepartment(department);
			employee.setName("li");
			session.save(employee);
			transaction.commit();

查询:

查询employee的时候可以得到外键关联的department对象。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值