对象模型的设计:
*********************
User.java
********************
package blog.hibernate.domain;
import java.util.Date;
public class User {
private int id;
private String name;
private Date birthday;
private Department depart;
public Department getDepart() {
return depart;
}
public void setDepart(Department depart) {
this.depart = 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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [birthday=" + birthday + ", depart=" + depart + ", id="
+ id + ", name=" + name + "]";
}
}
**********************
Department.java
*********************
package blog.hibernate.domain;
import java.util.Set;
public class Department {
private Integer id;
private String name;
private Set<User> users;
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
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;
}
@Override
public String toString() {
return "Department [id=" + id + ", name=" + name + ", users=" + users
+ "]";
}
}
******************
User.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="blog.hibernate.domain">
<class name="User" table="USERS">
<id name="id" column="USER_ID">
<generator class="native"></generator>
</id>
<property name="name" column="USER_NAME" type="string"></property>
<property name="birthday" column="BIRTHDAY" type="timestamp"></property>
<many-to-one name="depart" column="DEPART_ID" not-null="true"></many-to-one>
</class>
</hibernate-mapping>
******************
Department.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="blog.hibernate.domain">
<class name="Department" table="DEPARTMENTS">
<id name="id" column="DEPART_ID">
<generator class="native"></generator>
</id>
<property name="name" column="DEPART_NAME" type="string"></property>
<set name="users" >
<key column="DEPART_ID"></key>
<one-to-many class="User"/>
</set>
</class>
</hibernate-mapping>