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

简介: <p style="margin-left:0.74cm; margin-bottom:0cm"><span style="color:#000000"><span style="font-size:10px">如:</span><span style="font-family:Times New Roman,serif"><span style="font-family:Helvetic

如: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对象。



目录
相关文章
|
6月前
|
SQL XML Java
Hibernate - 单向多对一关联关系映射
Hibernate - 单向多对一关联关系映射
39 0
|
6月前
|
机器学习/深度学习 SQL Java
Hibernate - 多对多关联关系映射
Hibernate - 多对多关联关系映射
60 0
|
SQL Java 数据库连接
Nhibernate 一对一,一对多,多对多 成功映射
前语: 在Nhibernate xml 的文件配置上,一对一和多对多的配置比较简单,容易出错的反而是一对多(多对一)上。 1、一对一关联关系的映射: 序号 属性 含义和作用 必须 默认值 1 name 映射类属性的名字 Y   2 class 映射的目标类。
831 0