department.java
package cn.itcast.domain;
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;
}
}
Department.hbm.xml
<?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="cn.itcast.domain">
<class name="Department">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
package cn.itcast.domain;
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;
}
}
Employee.hbm.xml
<?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="cn.itcast.domain">
<class name="Employee">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<many-to-one name="depart" column="depart_id"></many-to-one>
</class>
</hibernate-mapping>
1 当配置多对一的关系的时候,当配置到类的时候,一个类肯定不是跟一个列对应,也就是说,在表当中我们 设置的是一个外键,但是在bean当中我们用的是一个类,这个时候many-to-one就可以设置为
<many-to-one name="depart" column="depart_id"></many-to-one>。默认depart_id是department的 主键。如果不是的话,property-ref就派上用场了。但是不推荐这么做
![](https://img-my.csdn.net/uploads/201207/04/1341409775_2802.png)