多对一的映射:
1: 在多的类中写加入一的类作为属性
2:depart一的一方不写其他属性只写自己的属性 自己的映射文件也是只写自己的映射
3:emp多的一方映射文件加入<many-to-one name="depart" column="depart_id"/>
column="depart_id"不写的话就默认字段为depart
代码如下:
Department类一的一方
package Entitys;
public class Department {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="Entitys">
<class name="Department">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
Employee多的一方
package Entitys;
public class Employee {
private int id;
private String name;
private Department depart;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepart() {
return depart;
}
public void setDepart(Department depart) {
this.depart = depart;
}
}
映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="Entitys">
<class name="Employee">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="depart" column="depart_id"/>
</class>
</hibernate-mapping>
/*
* 在对应的方法中,初始化代理就可以在查询完返回对象后可以
* 在在取得关联对象的信息,不必只在session中
*/
Hibernate.initialize(emp.getDepart());//是对应的属性的类
如果有<many-to-one name="depart" column="depart_id" not-null="true"/>
那么在必须有depart这个属性,并且在session中保存数据时s.save(depart)必须在s.save(emp)中要确保在emp有depart字段