Hibernate one-to-many relationships.

Hibernate one-to-many relationships.

How does one-to-many relationships works in hibernate?

View Answers

June 6, 2012 at 7:06 PM

Hibernate Mapping One-to-Many

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

We have two table ?

  1. Author.java
  2. Book.java

One author can write more than one book..So here is mapping one author to many books.

Author.java

package net.roseindia.table;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "author")
public class Author {

    private int id;
    private String name;

    private Set<Book> bookSet = new HashSet<Book>();

    public Author() {

    }

    public Author(String name, Set<Book> book) {
        this.name = name;
        this.bookSet = book;
    }

    @Id
    @GeneratedValue
    @Column(name = "id")
    public int getId() {
        return id;
    }

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

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(cascade = CascadeType.ALL)
    public Set<Book> getBookSet() {
        return bookSet;
    }

    public void setBookSet(Set<Book> bookSet) {
        this.bookSet = bookSet;
    }

}

Book.java

package net.roseindia.table;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
    private int id;
    private String tile;

    public Book() {

    }

    public Book(String title) {
        this.tile = title;
    }

    @Id
    @GeneratedValue
    @Column(name = "id")
    public int getId() {
        return id;
    }

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

    @Column(name = "title")
    public String getTile() {
        return tile;
    }

    public void setTile(String tile) {
        this.tile = tile;
    }

}

Continue....


June 6, 2012 at 7:08 PM

2. 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 class="net.roseindia.table.Book" />
        <mapping class="net.roseindia.table.Author" />

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

3.

Now create an util class as HibernateUtil.java.

package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

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

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

4.

Here is your main class-

package net.roseindia.application;

import java.util.HashSet;
import java.util.Set;

import net.roseindia.table.Author;
import net.roseindia.table.Book;
import net.roseindia.util.HibernateUtil;

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

public class OneToManyRelation {

    public static void main(String[] args) {


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

            Set<Book> books = new HashSet<Book>();
            books.add(new Book("Java"));
            books.add(new Book("C++"));

            Author author = new Author("Ratna", books);

            Transaction tr = session.beginTransaction();
            session.save(author);
            tr.commit();

            System.out.println("Done");

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

    }

}









Related Tutorials/Questions & Answers:
Hibernate one-to-many relationships.
Hibernate one-to-many relationships.  How does one-to-many relationships works in hibernate
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
Advertisements
Hibernate 4 One to Many mapping using XML
In this section, you will learn how to do one to many mapping of tables in Hibernate using Xml
Hibernet one-to-many prjection accessing - Hibernate
Hibernet one-to-many prjection accessing  Hai, I am Vinayak. I have Doubt in hibernate one-to-many accessing projection. Explanation of Question. I have a table PERSONAL and ADDRESS. PERSONAL is one to many association
Hibernate One to Many Self Join using Annotations
In this section, you will learn one to many self join using Annotations in Hibernate
Hibernate One to Many Indexed Mapping
In this section, you will learn to one to many indexed mapping in Hibernate to preserve mapping order
Hibernate 4 One to Many mapping using Annotation
In this section, you will learn how to do one to many mapping in Hibernate using Annotation
Hibernate 4 One to Many mapping using Annotation
In this section, you will learn how to do one to many mapping in Hibernate using Annotation
Hibernate One to Many Bi-directional Mapping
In this section, you will learn how to do One to Many Bi-Directional Mapping in Hibernate
Hibernate One to Many XML Mapping list Example
In this section, you will learn how to do one to many mapping using List to retain mapping order in Hibernate
Hibernate One to many XML mapping array Example
In this section, you will learn how to do one to many mapping using array to retain mapping order in Hibernate
Explain Hibernate Relationships with example.
databases support one-to-one, one-to-many, many-to-many and many-to-one relationships...Explain Hibernate Relationships with example.  Hello, Please explain various hibernate relationships. And if you can provide some examples
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...="custName" type="java.lang.String" column="custName" /> <many-to-one
Hibernate Relationships - Hibernate Relationships mapping example
-to-one, one-to-many, many-to-many and many-to-one relationships. We can... the example and see the data into database.   Hibernate one-to-many relationships example using hbm.xml file Here you will learn one-to-many
Resultset with one to many relationship
Resultset with one to many relationship   Suppose there are 5 tables in database named A,B,C,D and E. A has one to many relationship with B,C,D and D has one to many relationship with E. Beam class of A contains array of Class B
Hibernate One to many XML Mapping bag example
In this section, you will learn how to use element instead of or element in mapping XML file in Hibernate
Result Set one to many mapping
Result Set one to many mapping  Suppose there are 5 tables in database named A,B,C,D and E. A has one to many relationship with B,C,D and D has one to many relationship with E. Beam class of A contains array of Class B,C, and D
JPA One-to-Many Relationship
JPA One-to-Many Relationship     ... the one-to-many relationship and how to develop a one-to-many relation in your JPA Application. One-to-Many: In this relationship each record in Table-A may have
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-many persist children with its ID
jpa one-to-many persist children with its ID  I have two tables like Organization and region ,both table having one to many relationship.when i... persist the region table how? any one help me
one to many video chatting in web application
one to many video chatting in web application  Hi all....I am developing a web application,where video chatting is its one of the main feature.Can anybody tell me which technology to be used.Currently i am using Jsp and servlet
jpa one-to-many persist children with its ID
jpa one-to-many persist children with its ID  @Entity public class Item { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column... to change one-to-many's cascade persist behavoir, like persist Item first, then save
jpa one-to-many persist children with its ID by EntityListeners
jpa one-to-many persist children with its ID by EntityListeners  jpa one-to-many persist children with its ID by EntityListeners
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... tables with primary and foreign key relationships.ADS_TO_REPLACE_1 One-to-Many
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
Hibernate Relationships - Hibernate Relationships mapping example
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
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 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
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
Hibernate  How do you handle parent - child tables relationships in hibernate? How do you handle Detach state in hibernate
Hibernate Relationships - Settingup database
Hibernate Relationships - Settingup database       Hibernate Relationships... the Hibernate hbm2ddl utility to create/update the table structure at run
Hibernate Lazy Initialization
deal with one to many or many to many relationships in database.ADS_TO_REPLACE_1...Hibernate Lazy Initialization  What is lazy initialization in hibernate?   In Lazy Loading, Hibernate engine loads only those objects
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 mapping - Hibernate
hibernate mapping  when will we use one to one, one to many, many to many mapping... give a practical example
Database Tutorial: Introduction to Database Relationships
the facts in a single table.   One-to-many relationship...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
Hibernate 4 tutorials for beginners
relationships like one to one, one to many one to many XML, one to many induced mapping, many to many, many to many using XML etc and also available. View: Hibernate...Hibernate 4 tutorials for beginners We offer thousands of tutorials
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 Training
Application using Hibernate ORM Relationships Simple Association (one to one)  Basic Collection mapping (one-to-many) Simple unidirectional mapping (many-to-one)  Collection
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
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
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

Ads