`
liqita
  • 浏览: 291315 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Hibernate Mapping Many-to-One 实例 内附源代码及附件下载

阅读更多
Hibernate > Hibernate Mapping Many-to-One
Hibernate Mapping Many-to-One

In this example you will learn how to map many-to-one relationship using Hibernate. Consider the following relationship between Student and Address entity.

According to the relationship many students can have the same address.

To create this relationship you need to have a STUDENT and ADDRESS table. The relational model is shown below.

To create the STUDENT and ADDRESS table you need to create the following hibernate mapping files.

Student.hbm.xml is used to create the STUDENT table.
01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="com.vaannila.student.Student" table="STUDENT">
07.        <meta attribute="class-description">This class contains student details.</meta>
08.        <id name="studentId" type="long" column="STUDENT_ID">
09.            <generator class="native" />
10.        </id>
11.        <property name="studentName" type="string" length="100" not-null="true" column="STUDENT_NAME" />
12.        <many-to-one name="studentAddress" class="com.vaannila.student.Address" column="STUDENT_ADDRESS" cascade="all" not-null="true" />
13.    </class>
14.</hibernate-mapping>

The many-to-one element is used to create the many-to-one relationship between the Student and Address entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to all then all the operations will be cascaded. For instance when you save a Student object, the associated Address object will also be saved automatically.

Address.hbm.xml is used to create the ADDRESS table.
01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="com.vaannila.student.Address" table="ADDRESS">
07.        <meta attribute="class-description">This class contains the student's address
08.            details.</meta>
09.        <id name="addressId" type="long" column="ADDRESS_ID">
10.            <generator class="native" />
11.        </id>
12.        <property name="street" column="ADDRESS_STREET" type="string" length="250" />
13.        <property name="city" column="ADDRESS_CITY" type="string" length="50" />
14.        <property name="state" column="ADDRESS_STATE" type="string" length="50" />
15.        <property name="zipcode" column="ADDRESS_ZIPCODE" type="string" length="10" />
16.    </class>
17.</hibernate-mapping>

Now create the hibernate configuration file and add all the mapping files.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<!DOCTYPE hibernate-configuration PUBLIC
03.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
04.        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
05.<hibernate-configuration>
06.    <session-factory>
07.        <property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver </property>
08.        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost</property>
09.        <property name="hibernate.connection.username">sa</property>
10.        <property name="connection.password"></property>
11.        <property name="connection.pool_size">1</property>
12.        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
13.        <property name="show_sql">true</property>
14.        <property name="hbm2ddl.auto">create-drop</property>
15.        <mapping resource="com/vaannila/student/Student.hbm.xml"/>
16.        <mapping resource="com/vaannila/student/Address.hbm.xml"/>
17.    </session-factory>
18.</hibernate-configuration>

After creating the configuration file, generate java class files using Hibernate Tools.(To generate code using Hibernate Tools refer this example )

The following classes will be generated.
01.package com.vaannila.student;
02.
03.// Generated Sep 3, 2009 7:20:37 PM by Hibernate Tools 3.2.4.GA
04.
05./**
06. * This class contains student details.
07. */
08.public class Student implements java.io.Serializable {
09.
10.    private long studentId;
11.    private String studentName;
12.    private Address studentAddress;
13.
14.    public Student() {
15.    }
16.
17.    public Student(String studentName, Address studentAddress) {
18.        this.studentName = studentName;
19.        this.studentAddress = studentAddress;
20.    }
21.
22.    public long getStudentId() {
23.        return this.studentId;
24.    }
25.
26.    public void setStudentId(long studentId) {
27.        this.studentId = studentId;
28.    }
29.
30.    public String getStudentName() {
31.        return this.studentName;
32.    }
33.
34.    public void setStudentName(String studentName) {
35.        this.studentName = studentName;
36.    }
37.
38.    public Address getStudentAddress() {
39.        return this.studentAddress;
40.    }
41.
42.    public void setStudentAddress(Address studentAddress) {
43.        this.studentAddress = studentAddress;
44.    }
45.
46.}
01.package com.vaannila.student;
02.
03.// Generated Sep 3, 2009 7:20:37 PM by Hibernate Tools 3.2.4.GA
04.
05./**
06. * This class contains the student's address
07. *          details.
08. */
09.public class Address implements java.io.Serializable {
10.
11.    private long addressId;
12.    private String street;
13.    private String city;
14.    private String state;
15.    private String zipcode;
16.
17.    public Address() {
18.    }
19.
20.    public Address(String street, String city, String state, String zipcode) {
21.        this.street = street;
22.        this.city = city;
23.        this.state = state;
24.        this.zipcode = zipcode;
25.    }
26.
27.    public long getAddressId() {
28.        return this.addressId;
29.    }
30.
31.    public void setAddressId(long addressId) {
32.        this.addressId = addressId;
33.    }
34.
35.    public String getStreet() {
36.        return this.street;
37.    }
38.
39.    public void setStreet(String street) {
40.        this.street = street;
41.    }
42.
43.    public String getCity() {
44.        return this.city;
45.    }
46.
47.    public void setCity(String city) {
48.        this.city = city;
49.    }
50.
51.    public String getState() {
52.        return this.state;
53.    }
54.
55.    public void setState(String state) {
56.        this.state = state;
57.    }
58.
59.    public String getZipcode() {
60.        return this.zipcode;
61.    }
62.
63.    public void setZipcode(String zipcode) {
64.        this.zipcode = zipcode;
65.    }
66.
67.}

Create the Main class to run the example.
01.package com.vaannila.student;
02.
03.import org.hibernate.HibernateException;
04.import org.hibernate.Session;
05.import org.hibernate.Transaction;
06.
07.import com.vaannila.util.HibernateUtil;
08.
09.public class Main {
10.
11.    public static void main(String[] args) {
12.        Session session = HibernateUtil.getSessionFactory().openSession();
13.        Transaction transaction = null;
14.        try {
15.            transaction = session.beginTransaction();
16.            Address address = new Address("OMR Road", "Chennai", "TN", "600097");
17.            //By using cascade=all option the address need not be saved explicitly when the student object is persisted the address will be automatically saved.
18.            //session.save(address);
19.            Student student1 = new Student("Eswar", address);
20.            Student student2 = new Student("Joe", address);
21.            session.save(student1);
22.            session.save(student2);
23.            transaction.commit();
24.        } catch (HibernateException e) {
25.            transaction.rollback();
26.            e.printStackTrace();
27.        } finally {
28.            session.close();
29.        }
30.
31.    }
32.
33.}

On executing the Main class you will see the following output.

The Student table has two records.

The Address table has one record.

Both the student records points to the same address record, this illustrates the many-to-one mapping.

The folder structure of the example is shown below.

You can download the source code of this example here.
Sourceownload
分享到:
评论

相关推荐

    hibernate源码 直接使用

    一对一(One-to-One)、一对多(One-to-Many)和多对多(Many-to-Many)是实体间的关系类型,它们在数据库设计中广泛存在,并且Hibernate提供了强大的支持来处理这些关联。 **Hibernate核心概念** 1. **实体...

    HibernateAPI中文版.chm

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    hibernate3.2中文文档(chm格式)

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    hibernate doc 中文版

    - **Mapping one-to-one and one-to-many associations:** - 映射一对一和一对多关联的方法。 - **自然ID(natural-id):** - 自然标识符的概念及其实现。 以上内容概述了从《hibernate doc 中文版》文档中提取...

    Hibernate+中文文档

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    hibernate中文参考文档

    - **概述**: Hibernate是一个开放源代码的对象关系映射(ORM)框架,它对JDBC进行了非常轻量级的对象封装,使Java开发人员能够以面向对象的方式操作数据库。 #### 二、基本概念 - **ORM (Object Relational Mapping...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    5.1.10. 多对一(many-to-one) 5.1.11. 一对一 5.1.12. 自然ID(natural-id) 5.1.13. 组件(component), 动态组件(dynamic-component) 5.1.14. properties 5.1.15. 子类(subclass) 5.1.16. 连接的子类(joined-...

    Hibernate映射关系配置:XML方式和注解方式

    3. **关联映射**:XML映射文件中可以定义一对多、一对一、多对多等各种关系,比如使用`&lt;set&gt;`, `&lt;one-to-one&gt;`, `&lt;many-to-many&gt;`等元素。 **注解方式** 1. **@Entity**:这个注解标记一个Java类为Hibernate实体,...

    Hibernate学习.pdf

    - **多对一(many-to-one)**: 实体间的多对一关系。 - **一对一(one-to-one)**: 实体间的一对一关系。 #### 7. 组件映射 - **组件映射**: 将Java对象中的某个属性映射为数据库表中的多个字段。 #### 8. 继承...

    Hibernate 参考文档

    - **多对一(many-to-one)**:表示一对多关系的逆向映射。 - **一对一**:一对一关系的映射方法。 - **组件(component)**:复合对象的映射。 - **子类(subclass)**:继承体系中的子类映射。 - **连接的子类...

    Hibernate一对多映射

    在Java的持久化框架Hibernate中,一对多映射(One-to-Many Mapping)是一种常见的关系映射类型,它反映了数据库中表与表之间的关联关系。本文将深入探讨Hibernate一对多映射的概念、配置以及实现方式,并结合提供的...

    hibernate多表操作实例代码

    &lt;many-to-one name="department" column="departmentId" class="Department"&gt;&lt;/many-to-one&gt; ``` - 在Department的映射文件中,添加`&lt;set&gt;`和`&lt;one-to-many&gt;`标签: ```xml &lt;key column="departmentId"&gt;&lt;/...

    XDoclet Tags

    XDoclet是一款强大的Java源代码注解处理器,它能够自动根据源代码中的注释生成各种元数据文件,如Hibernate的映射文件、EJB的部署描述符等。在使用XDoclet时,我们需要理解并正确使用一系列特定的标签,这些标签在...

    Hibernate多对一映射

    **正文** Hibernate是一款强大的Java持久化框架,它简化了数据库操作,使得开发...提供的压缩包文件`hibernate_many2one`可能包含了相关的源代码、测试用例和映射文档,你可以下载并参考这些资源进一步实践和学习。

    Hibernate经典例题源码(超全)

    9. **一对多(One-to-Many)、多对一(Many-to-One)关系映射**: Hibernate支持不同类型的关联关系,如实体类之间的一对多、多对一关系,通过`@OneToMany`和`@ManyToOne`注解实现。 10. **多对多(Many-to-Many)...

    Hibernate学习总结

    Hibernate是一个开放源代码的ORM(Object Relational Mapping)框架,它对JDBC进行了非常轻量级的对象封装,使得Java开发人员可以使用对象编程思想来操作数据库。Hibernate主要特点包括自动SQL生成、透明持久化、面向...

    nhibernate reference

    5.1.11 many-to-one元素,用于映射多对一关系。 5.1.12 one-to-one元素,用于映射一对一关系。 5.1.13 natural-id元素,用于映射自然ID。 5.1.14 component和dynamic-component元素,用于映射组件类型。 5.1.15 ...

Global site tag (gtag.js) - Google Analytics