Hibernate one-to-one relationships

How does one to one relationship work in Hibernate?

View Answers

June 6, 2012 at 6:54 PM

Hibernate Mapping One-to-One

Hibernate provides facility of mapping. You can do mapping through hbm.xml or through annotation. here is an example showing one to one relationship using hbm.xml.

We have two table ?

1.Customer(id,name)

2.Invoice(id,another_field)

Steps to cover this example as-

1.put hibernate library in to lib folder in src.

2.Create getter-setter of table.

Customer.java

package net.roseindia.table;
public class Customer {

    private int id;

    private String custName;

    private Invoice invoice;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public Invoice getInvoice() {
        return invoice;
    }

    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }

}

Invoice.java

package net.roseindia.table;

public class Invoice {

    private int id;

    private String anotherField;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAnotherField() {
        return anotherField;
    }

    public void setAnotherField(String anotherField) {
        this.anotherField = anotherField;
    }

}

Now map the tables by using hbm.xml.Each table has its own hbm.xml.

Customer.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>
    <class name="net.roseindia.table.Customer" table="Customer">
        <id name="id" type="int" column="Cus_id">
            <generator class="native" />
        </id>
        <property name="custName" type="java.lang.String" column="custName" />

        <many-to-one name="invoice" class="net.roseindia.table.Invoice"
            column="id" not-null="true" cascade="all" unique="true" />
    </class>
</hibernate-mapping>

Invoice.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>
    <class name="net.roseindia.table.Invoice" table="Invoice">
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="anotherField" type="java.lang.String" column="anotherField" />
    </class>
</hibernate-mapping>

June 6, 2012 at 6:57 PM

Next step -

3. hibernate-cfg.xml is configuration file saved in the same folder where the source code of class file is saved. It creates the connection pool and set-up required environment.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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/hibernateRelationShip</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>

        <!-- Mapping files -->
        <mapping resource="Invoice.hbm.xml" />
        <mapping resource="Customer.hbm.xml" />

    </session-factory>
</hibernate-configuration>

4. Now create an util class as HibernateUtil.java package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory sessionFactory = null;
    static {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Continue....


June 6, 2012 at 6:59 PM

Here is next step- 5 Here is your main class.

package net.roseindia.application;

import net.roseindia.table.Customer;
import net.roseindia.table.Invoice;
import net.roseindia.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class OneToOneRelation {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        SessionFactory sessFact = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();

            // Create Customer Object
            Customer cust = new Customer();
            // /cust.setId(1);
            cust.setCustName("Ratna");
            // Invoice object
            Invoice inv = new Invoice();
            // Set some values in invoice
            inv.setAnotherField("Ratna Invoice");

            cust.setInvoice(inv);// Set invoice object to customer object
            Transaction tr = session.beginTransaction();
            session.save(cust);
            tr.commit();

            System.out.println("Done");

        } catch (HibernateException he) {
            System.out.println(he.getMessage());
        } finally {
            // SessionFactory close
             session.close();
        }

    }

}

Description: For creating one to one relationship we use many-to-one element. We can achieve this by making Invoice column unique in the Customer.









Related Tutorials/Questions & Answers:
Hibernate one-to-one relationships
Hibernate one-to-one relationships  How does one to one relationship work in Hibernate?   Hibernate Mapping One-to-One Hibernate provides.... here is an example showing one to one relationship using hbm.xml. We have two
Hibernate One-to-one Relationships
Hibernate One-to-one Relationships       Hibernate One-to-one Relationships...-to-one relationships in Hibernate. In next section we will learn how
Advertisements
Give a one to one example in Hibernate.
to one relationships in hibernate, you can go through the following links: Hibernate One-to-one Relationships Hibernate One to One Bi-directional Mapping...Give a one to one example in Hibernate.  Hello, Can you give me one
What is Hibernate one to one relation?Any example..
Relationships and other Hibernate Relationships.. Hibernate One-to-one Relationships Hibernate Relationships mapping example Hibernate 4 One to One Mapping...What is Hibernate one to one relation?Any example..  Hello, What
Hibernate one to one mapping using xml
address. Check the example at: Hibernate One-to-one Relationships Thanks...Hibernate one to one mapping using xml  Hi, How to create hibernate one to one mapping using xml? I have to create the mapping using the *.hbm.xml
Hibernate One to One Mapping using XML
In this section, you will learn One to One mapping of table in Hibernate using Xml
Hibernate One to One Bi-directional Mapping
In this section, you will learn one to one bi-directional mapping in Hibernate
Explain Hibernate Relationships with example.
Explain Hibernate Relationships with example.  Hello, Please explain various hibernate relationships. And if you can provide some examples... databases support one-to-one, one-to-many, many-to-many and many-to-one relationships
Hibernate 4 One to One Mapping using Annotation
Hibernate One to One Mapping using Annotation
Hibernate 4 One to One Mapping using Annotation
Hibernate One to One Mapping using Annotation
Can you give me Hibernate one to one example?
Can you give me Hibernate one to one example?  Hello there, Can you give me a hibernate one to one example that explain the concept and mapping in Hibernate. Thanks in advance
Hibernate one-to-many relationships.
Hibernate one-to-many relationships.  How does one-to-many relationships works in hibernate
Hibernate Relationships - Hibernate Relationships mapping example
Hibernate Relationships - Hibernate Relationships mapping example... IDE can be used to run the Hibernate Relationships examples. You can easily...-to-one, one-to-many, many-to-many and many-to-one relationships. We can
Hibernate Many One One Mapping
Hibernate Mapping And Join Using hibernate we can easily create relationship between two tables. The relationship may be One-To-One, One-To-Many, Many-To-One and Many-To-Many. An Example of One To Many mapping is given below Address
jsp one to one mapping
jsp one to one mapping  how to perform one to one mapping in jsp....code of one to one mapping with .xml file
Hibernate Many-to-one Relationships
Hibernate Many-to-one Relationships       Hibernate Many-to-one Relationships - Many to one relationships example using xml meta-data This current
JPA One-to-One Relationship
JPA One-to-One Relationship   ... will learn  about the one-to-one relationship. In the one-to-one relation mapping a single value association to another entity.  One-to-One: In one-to-one
How to create one to one relationship in Hibernate 4 with Annotation?
How to create one to one relationship in Hibernate 4 with Annotation? In this tutorial we are developing an application in Hibernate 4 to create one...); } System.out.println("Example : Hibernate One to One Mapping using Annotation "
Hibernate One-to-many Relationships
Hibernate One-to-many Relationships       Hibernate One-to-many Relationships - One to many example code in Hibernate using the xml file as metadata. Here
ModuleNotFoundError: No module named 'django-auto-one-to-one'
ModuleNotFoundError: No module named 'django-auto-one-to-one'  Hi...: No module named 'django-auto-one-to-one' How to remove the ModuleNotFoundError: No module named 'django-auto-one-to-one' error? Thanks   Hi
types of relationships in tables
types of relationships in tables  How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?   hi, One-to-One relationship can be implemented as a single table and rarely as two
Spliting Large XML and one by one Moved to Output Folder
Spliting Large XML and one by one Moved to Output Folder  How to Spliting Large XML and one by one Moved to Output Folder
one-to-one bidirectional association between an abstract class and a persistent class
one-to-one bidirectional association between an abstract class and a persistent class  How do I define a bidirectional one to one association between an abstract class and a persistent class? Please help
How to fetch entries/values from database to a jsp page one by one?
How to fetch entries/values from database to a jsp page one by one?  I have a table in Microsoft SQL server Management Studio with two columns title and data and each column has 10 enteries. I have a jsp page on which i want
ModuleNotFoundError: No module named 'relationships'
ModuleNotFoundError: No module named 'relationships'  Hi, My... 'relationships' How to remove the ModuleNotFoundError: No module named 'relationships' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'django-relationships'
ModuleNotFoundError: No module named 'django-relationships'  Hi...: No module named 'django-relationships' How to remove the ModuleNotFoundError: No module named 'django-relationships' error? Thanks   Hi
ModuleNotFoundError: No module named 'django-relationships'
ModuleNotFoundError: No module named 'django-relationships'  Hi...: No module named 'django-relationships' How to remove the ModuleNotFoundError: No module named 'django-relationships' error? Thanks   Hi
ModuleNotFoundError: No module named 'django-relationships'
ModuleNotFoundError: No module named 'django-relationships'  Hi...: No module named 'django-relationships' How to remove the ModuleNotFoundError: No module named 'django-relationships' error? Thanks   Hi
Hibernate Relationships - Settingup database
Hibernate Relationships - Settingup database       Hibernate Relationships... the Hibernate hbm2ddl utility to create/update the table structure at run
Hibernate
Hibernate  How do you handle parent - child tables relationships in hibernate? How do you handle Detach state in hibernate
Hibernate Many-to-many Relationships
; In this section we learned about the Many-to-one relationships in Hibernate... Hibernate Many-to-many Relationships... Relationships - Many to many example in Hibernate. In this example we have used xml
java - Hibernate
java  how can we configure many to many relationships in hibernate
ModuleNotFoundError: No module named 'discover-feature-relationships'
ModuleNotFoundError: No module named 'discover-feature-relationships' ...: No module named 'discover-feature-relationships' How to remove the ModuleNotFoundError: No module named 'discover-feature-relationships' error
Hibernate association and join example
relationships. You will also learn how to present these relationships in Hibernate. Hibernate relationships eases the development of persistence layer of complex application involving various types of relationships such as one-to-one, one
hibernate
hibernate  can any one one explain what is hibernate ?   Please visit the following link: Hibernate Tutorials
Database Tutorial: Introduction to Database Relationships
Database Relationships: An Introduction to Foreign Keys, Joins and E-R... relationships which has been named as per the need and function of the types and exists between two data based tables.ADS_TO_REPLACE_1 One-to-one
hibernate mapping - Hibernate
hibernate mapping  when will we use one to one, one to many, many to many mapping... give a practical example
Hibernate One To Mapping
Hibernate One To One Mapping Using Annotation Hi If you are use-to with the Hibernate annotation, then it is very simple to do mapping using hibernate annotation Consider a relationship between a Student and a Address, where One Student
Hibernate 4 tutorials for beginners
relationships like one to one, one to many one to many XML, one to many induced mapping...Hibernate 4 tutorials for beginners We offer thousands of tutorials on hibernate. You can definitely visit the hibernate section to learn about the tutorials
Parent child windows relationships when webpage is accesssed through a hyperlink.
Parent child windows relationships when webpage is accesssed through a hyperlink.  A particular session timeout functionality works when a webpage is loaded. The webpage has parent/child windows. This timeout functionality works
j2eee(Hibernate) - Hibernate
j2eee(Hibernate)  Hi, This is jagadhish.Iam learning Hibernate.I have one doubt on relationships in Hibernate.plz anybody tell me how to use relations in Hibernate(with examples).But not showing the link available
HIBERNATE
HIBERNATE   What is difference between Jdbc and Hibernate
hibernate
hibernate  what is hibernate flow
hibernate
hibernate  what is hibernate listeners
hibernate
hibernate  how to uses optional column in hibernate
hibernate
hibernate  please give me the link where i can freely download hibernate software(with dependencies)   Learn hibernate, if you want to learn hibernate, please visit the following link: Hibernate Tutorials
Hibernate
Hibernate  hibernate delete query execution
hibernate
hibernate  what is hibernate why we use
Hibernate
Hibernate  how to use pagination concept in Hibernate