以教师表为例,教师表中还有个Name类嵌套,但是这是如果想把Name表中的两个属性也加在Teacher表中,这时就需要用到组建关联。
package cn.itcast.hibernate.domain;
import java.util.Set;
public class Teacher {
private int id;
private Name name;
private Set<Student> students;
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 Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
/**************************************************************************/
Name.java
package cn.itcast.hibernate.domain;
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
/*******************************************************************************/
这时需要在Teacher.hbm.xml映射文件里做如下配置:
<?xml version="1.0"?>
<!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.hibernate.domain">
<class name="Teacher">
<id name="id" column="teacher_id">
<generator class="native"/>
</id>
<!--<property name="name" column="teacher_name"/>
-->
<component name="name" class="Name">
<property name="firstName" column="first_name"></property>
<property name="lastName" column="last_name"></property>
</component>
<set name="students" table="teacher_student">
<key column="teacher_id"></key>
<many-to-many class="Student" column="student_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
/******************************************************************************/
这样就会在一个表里: