Hibernate One-To-One Mapping Tutorial

Hibernate One-To-One Mapping Tutorial

转,整理。

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

 

According to the relationship each student should have a unique 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.

In Mysql, use bigint as long int.

create table address(address_Id bigint primary key auto_increment, address_street varchar(30) not null, address_city varchar(30) not null,state varchar(30) not null, address_zipcode varchar(30) not null);

 

create table student(student_Id bigint primary key auto_increment, student_name varchar(30) not null, student_address bigint not null);

 

Student.hbm.xml is used to create the STUDENT table.

<?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>

    <class name="com.vaannila.student.Student" table="STUDENT">

        <meta attribute="class-description">This class contains student details.</meta>

        <id name="studentId" type="long" column="STUDENT_ID">

            <generator class="native" />

        </id>

        <property name="studentName" type="string" not-null="true" length="100" column="STUDENT_NAME" />

        <many-to-one name="studentAddress" class="com.vaannila.student.Address" column="STUDENT_ADDRESS" not-null="true" cascade="all" unique="true" />

    </class>

</hibernate-mapping>

 

 

We use the many-to-one element to create the one-to-one relationship between the Student and Address entities. We do this my making the STUDENT_ADDRESS column unique in the STUDENT table.

 

Address.hbm.xml is used to create the ADDRESS table.

<?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>

       <class name="com.vaannila.student.Address" table="ADDRESS">

              <meta attribute="class-description">This class contains the student's address

                     details.</meta>

              <id name="addressId" type="long" column="ADDRESS_ID">

                     <generator class="native" />

              </id>

              <property name="street" column="ADDRESS_STREET" type="string" length="250" />

              <property name="city" column="ADDRESS_CITY" type="string" length="50" />

              <property name="state" column="ADDRESS_STATE" type="string" length="50" />

              <property name="zipcode" column="ADDRESS_ZIPCODE" type="string" length="10" />

       </class>

</hibernate-mapping>

 

 

 

?Now create the hibernate configuration file and add all the mapping files.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

              "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/md11utf8</property>

        <property name="hibernate.connection.username">root</property>

        <property name="connection.password">root</property>

        <property name="connection.pool_size">1</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">create</property>

        <mapping resource="com/vaannila/student/Student.hbm.xml"/>

        <mapping resource="com/vaannila/student/Address.hbm.xml"/>

    </session-factory>

</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.

package com.vaannila.student;

 

// Generated Sep 3, 2009 7:20:37 PM by Hibernate Tools 3.2.4.GA

 

/**

 * This class contains the student's address

 *                   details.

 */

public class Address implements java.io.Serializable {

 

       private long addressId;

       private String street;

       private String city;

       private String state;

       private String zipcode;

 

       public Address() {

       }

 

       public Address(String street, String city, String state, String zipcode) {

              this.street = street;

              this.city = city;

              this.state = state;

              this.zipcode = zipcode;

       }

 

       public long getAddressId() {

              return this.addressId;

       }

 

       public void setAddressId(long addressId) {

              this.addressId = addressId;

       }

 

       public String getStreet() {

              return this.street;

       }

 

       public void setStreet(String street) {

              this.street = street;

       }

 

       public String getCity() {

              return this.city;

       }

 

       public void setCity(String city) {

              this.city = city;

       }

 

       public String getState() {

              return this.state;

       }

 

       public void setState(String state) {

              this.state = state;

       }

 

       public String getZipcode() {

              return this.zipcode;

       }

 

       public void setZipcode(String zipcode) {

              this.zipcode = zipcode;

       }

 

}

 

 

package com.vaannila.student;

 

// Generated Sep 3, 2009 7:20:37 PM by Hibernate Tools 3.2.4.GA

 

/**

 * This class contains student details.

 */

public class Student implements java.io.Serializable {

 

       private long studentId;

       private String studentName;

       private Address studentAddress;

 

       public Student() {

       }

 

       public Student(String studentName, Address studentAddress) {

              this.studentName = studentName;

              this.studentAddress = studentAddress;

       }

 

       public long getStudentId() {

              return this.studentId;

       }

 

       public void setStudentId(long studentId) {

              this.studentId = studentId;

       }

 

       public String getStudentName() {

              return this.studentName;

       }

 

       public void setStudentName(String studentName) {

              this.studentName = studentName;

       }

 

       public Address getStudentAddress() {

              return this.studentAddress;

       }

 

       public void setStudentAddress(Address studentAddress) {

              this.studentAddress = studentAddress;

       }

 

}

 

 

Create the Main class to run the example.

 

package com.vaannila.student;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.vaannila.util.HibernateUtil;

 

public class Main {

 

            public static void main(String[] args) {

                        Session session = HibernateUtil.getSessionFactory().openSession();

                        Transaction transaction = null;

                        try {

                                    transaction = session.beginTransaction();

                                    Address address1 = new Address("OMR Road", "Chennai", "TN", "600097");

                                    Address address2 = new Address("Ring Road", "Banglore", "Karnataka", "560000");

                                    Student student1 = new Student("Eswar", address1);

                                    Student student2 = new Student("Joe", address2);

                                    session.save(student1);

                                    session.save(student2);

                                    transaction.commit();              

                                   

                        } catch (HibernateException e) {

                                    transaction.rollback();

                                    e.printStackTrace();

                        } finally {

                                    session.close();

                        }

 

            }

 

}

 

 

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

The Student table has two records.

 

The Address table has two record.

 

Each student record points to a different address record, this illustrates the one-to-one mapping.

The folder structure of the example is shown below.

 

 

posted @ 2013-03-16 20:36  清净的雨天  阅读(548)  评论(0编辑  收藏  举报