1、Annotation
Group.java
 1package com.bebig.hibernate.model;
 2
 3import javax.persistence.Entity;
 4import javax.persistence.GeneratedValue;
 5import javax.persistence.Id;
 6import javax.persistence.Table;
 7
 8@Entity
 9@Table(name="t_group")
10public class Group {
11    private int id;
12
13    private String name;
14
15    @Id
16    @GeneratedValue
17    public int getId() {
18        return id;
19    }

20
21    public String getName() {
22        return name;
23    }

24
25    public void setId(int id) {
26        this.id = id;
27    }

28
29    public void setName(String name) {
30        this.name = name;
31    }

32}

33
User.java
 1package com.bebig.hibernate.model;
 2
 3import javax.persistence.Entity;
 4import javax.persistence.GeneratedValue;
 5import javax.persistence.Id;
 6import javax.persistence.ManyToOne;
 7import javax.persistence.Table;
 8
 9@Entity
10@Table(name="t_user")
11public class User {
12    private int id;
13
14    private String name;
15
16    private Group group;
17
18    @ManyToOne
19    public Group getGroup() {
20        return group;
21    }

22
23    @Id
24    @GeneratedValue
25    public int getId() {
26        return id;
27    }

28
29    public String getName() {
30        return name;
31    }

32
33    public void setGroup(Group group) {
34        this.group = group;
35    }

36
37    public void setId(int id) {
38        this.id = id;
39    }

40
41    public void setName(String name) {
42        this.name = name;
43    }

44}

45
hibernate.cfg.xml
1         <mapping class="com.bebig.hibernate.model.Group"/> 
2         <mapping class="com.bebig.hibernate.model.User"/> 
2、XML
两个类文件不变,修改hibernate.cfg.xml,并增加两个类映射XML文件。
Group.hbm.xml
 1<?xml version="1.0"?>
 2<!DOCTYPE hibernate-mapping PUBLIC
 3        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5
 6<hibernate-mapping package="com.bebig.hibernate.model">
 7    <class name="Group" table="t_group">
 8        <id name="id">
 9            <generator class="native"></generator>
10        </id>
11        <property name="name"></property>
12    </class>
13</hibernate-mapping>
User.hbm.xml
 1<?xml version="1.0"?>
 2<!DOCTYPE hibernate-mapping PUBLIC
 3        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5
 6<hibernate-mapping package="com.bebig.hibernate.model">
 7    <class name="User" table="t_user">
 8        <id name="id">
 9            <generator class="native"></generator>
10        </id>
11        <property name="name"></property>
12        <many-to-one name="group" column="groupId"></many-to-one>
13    </class>
14</hibernate-mapping>
hibernate.cfg.xml
1<mapping resource="com/bebig/hibernate/model/Group.hbm.xml" />
2        <mapping resource="com/bebig/hibernate/model/User.hbm.xml" />