Home Answers Viewqa Hibernate Hibernate one-to-many relationships.

 
 


ratna rathor
Hibernate one-to-many relationships.
2 Answer(s)      11 months ago
Posted in : Hibernate

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 Pages:
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... mapping in Hibernate. Many to many relationships is interesting as one
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 Relationships - Hibernate Relationships mapping example
into database.   Hibernate one-to-many relationships example using....   Hibernate many-to-one relationships example using hbm.xml...-to-one, one-to-many, many-to-many and many-to-one relationships. We can
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 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
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 One to Many Self Join using Annotations
In this section, you will learn one to many self join using Annotations in Hibernate
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
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
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
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 Bi-directional Mapping
In this section, you will learn how to do One to Many Bi-Directional Mapping in Hibernate
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-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
types of relationships in tables
tables with primary and foreign key relationships. One-to-Many relationships...types of relationships in tables  How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?   hi
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 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
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
Hibernate
Hibernate  How do you handle parent - child tables relationships in hibernate? How do you handle Detach state in hibernate
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
Hibernate Relationships - Settingup database
Hibernate Relationships - Settingup database       Hibernate Relationships... the one-to-one mapping in Hibernate
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
Hibernate Lazy Initialization
deal with one to many or many to many relationships in database. An attribute...Hibernate Lazy Initialization  What is lazy initialization in hibernate?   In Lazy Loading, Hibernate engine loads only those objects
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
java - Hibernate
java  how can we configure many to many relationships in hibernate
hibernate mapping - Hibernate
hibernate mapping  when will we use one to one, one to many, many to many mapping... give a practical example
Identify correct and incorrect statements or examples about persistent relationships, remove protocols, and about the abstract schema type of a CMP entity bean.
). Relationships may be one-to-one, one-to-many, or many-to-many relationships... or many-to-one relationship to the entity will return null; and an accessor... be specified for a many-to-many relationship. The deletion of one entity
Hibernate Training
a simple CRUD Application using Hibernate ORM Relationships... (one-to-many) Simple unidirectional mapping (many-to-one)  Collection (many to many)  Examples: Setting up one to one, one
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 Association
Hibernate Association  1) <bag name="product" inverse="true" cascade="all,delete-orphan"> <key column="did"/> <one-to-many class="net.roseindia.Product"/> </bag> 2) <many-to-one
Mapping Technics - Hibernate
Mapping Technics  Hai i want some clarifications about one-to-many bidirectional relationship
Complete Hibernate 4.0 Tutorial
XML Hibernate One to Many Mapping using Annotation Hibernate One to Many Mapping using XML Hibernate... Hibernate One to Many XML Mapping <list> Example Hibernate
HIBERNATE- BASICS
HIBERNATE- BASICS  (R.S.Ramaswamy)- ( in 3 parts) (part-1) ( CMP-EJB vs. HIBERNATE) (published in DeveloperIQ-July-2005... is agog with excitement about a very popular open-source technology , Hibernate
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
HIBERNATE
HIBERNATE   What is difference between Jdbc and Hibernate
hibernate
hibernate  what is hibernate listeners
hibernate
hibernate  what is hibernate flow
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
hibernate
hibernate   I want to learn how to use hibernate framework in web application . for storing database in our application
hibernate
hibernate   I want to learn how to use hibernate framework in web application . for storing database in our application
hibernate
why hibernate?  why hibernate?   Hibernate: -Hibernate... library. It solves object-relational impedance mismatch problems. Hibernate makes the application development process easy Hibernate saves the development

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.