Sunday, 3 February 2013

Hibernate one to many mapping example

This is 4 of 8 parts of tutorial series

Tutorial Content:

Part-1:Introduction to hibernate framework
Part-2:Hibernate hello world example in eclipse
Part-3:Hibernate one to one mapping example
Part-4:Hibernate one to many mapping example
Part-5:Hibernate many to many mapping example
Part-6:Hibernate inheritance:Table per class hierarchy
Part-7:Hibernate inheritance:table per subclass
Part-8:Hibernate inheritance:Table per concrete class 
 
In this example we will see how to implement one to many relationship using annotations.
Lets take example of Country and state.One Country can have n number of states.Following is relationship diagram among them.


Now to create above tables in database, you need to create two java files i.e. Country.java and State.java.

1.Country.java

Country class will be used to create COUNTRY table in database.
Create Country.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="COUNTRY")
public class Country {
 
 @Id
 @Column(name="Country_Name")
 String countryName ;
    
 @OneToMany(cascade=CascadeType.ALL)
 @JoinTable(name="COUNTRY_STATE",joinColumns={@JoinColumn(name="Country_Name")},inverseJoinColumns={@JoinColumn(name="State_Name")})
 Collection<State> listOfStates=new ArrayList<State>();
     
    @Column(name="Country_Population")
    long countryPopulation;
        
    public Country()
    {
     
    }
    
    public Country(String countryName, long countryPopulation) {
  this.countryName = countryName;
  this.countryPopulation = countryPopulation;
 }

   public long getCountryPopulation() {
  return countryPopulation;
 }

 public void setCountryPopulation(long countryPopulation) {
  this.countryPopulation = countryPopulation;
 }

 public String getCountryName() {
        return countryName;
    }
          
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

 public Collection<State> getListOfStates() {
  return listOfStates;
 }

 public void setListOfStates(Collection<State> listOfStates) {
  this.listOfStates = listOfStates;
 }
}

The @OneToMany annotation is used to create the one-to-many relationship between the Country and State entities. The @JoinTable annotation is used to create the COUNTRY_STATE link table and @JoinColumn annotation is used to refer the linking columns in both the tables.

2.State.java

State class will be used to create STATE table in database.
Create State.java in src->org.arpit.javapostsforlearning.

package org.arpit.javapostsforlearning;import javax.persistence.Column;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="STATE")
public class State {

 @Id
 @Column(name="State_Name")
 private String stateName;
 @Column(name="State_Population")
    long statePopulation;
 
 public State()
 {
  
 }
 public State(String stateName, long statePopulation) {
  super();
  this.stateName = stateName;
  this.statePopulation = statePopulation;
 }

 public String getStateName() {
  return stateName;
 }

 public void setStateName(String stateName) {
  this.stateName = stateName;
 }

 public long getStatePopulation() {
  return statePopulation;
 }

 public void setStatePopulation(long statePopulation) {
  this.statePopulation = statePopulation;
 }
}

3.Hiberante.cfg.xml:

Create a file named "hibernate.cfg.xml" in src folder.
<?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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

  <mapping class="org.arpit.javapostsforlearning.Country"></mapping>
  <mapping class="org.arpit.javapostsforlearning.State"></mapping>

    </session-factory>

</hibernate-configuration>

4.Main Class:

package org.arpit.javapostsforlearning;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMain {

 public static void main(String[] args) {
  
  Country countryIndia=new Country("India",50000000);
  
  State mpState=new State("Madhya Pradesh",1000000);
  State maharastraState=new State("Maharastra",2000000);
  
  countryIndia.getListOfStates().add(mpState);
  countryIndia.getListOfStates().add(maharastraState);
    
  Configuration configuration=new Configuration();
  configuration.configure();
  ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  SessionFactory sf=configuration.buildSessionFactory(sr);
  Session ss=sf.openSession();
  
  ss.beginTransaction();
  ss.save(countryIndia);
  ss.getTransaction().commit();
  ss.close();
  
 }

}

Project Struture:

 

5.Run it:

When you run it,you will get following output.

Hibernate: create table COUNTRY (Country_Name varchar(255) not null, Country_Population bigint, primary key (Country_Name))
Hibernate: create table COUNTRY_STATE (Country_Name varchar(255) not null, State_Name varchar(255) not null, unique (State_Name))
Hibernate: create table STATE (State_Name varchar(255) not null, State_Population bigint, primary key (State_Name))
Hibernate: alter table COUNTRY_STATE add constraint FKA1E1226881D857C0 foreign key (State_Name) references STATE
Hibernate: alter table COUNTRY_STATE add constraint FKA1E1226865CEDD60 foreign key (Country_Name) references COUNTRY
Feb 02, 2013 10:26:07 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: select state_.State_Name, state_.State_Population as State2_1_ from STATE state_ where state_.State_Name=?
Hibernate: select state_.State_Name, state_.State_Population as State2_1_ from STATE state_ where state_.State_Name=?
Hibernate: insert into COUNTRY (Country_Population, Country_Name) values (?, ?)
Hibernate: insert into STATE (State_Population, State_Name) values (?, ?)
Hibernate: insert into STATE (State_Population, State_Name) values (?, ?)
Hibernate: insert into COUNTRY_STATE (Country_Name, State_Name) values (?, ?)
Hibernate: insert into COUNTRY_STATE (Country_Name, State_Name) values (?, ?)

 

6.SQL output:

COUNTRY table in database




STATE table in database





COUNTRY_STATE table is created to link above two tables.



Source code:

 

Java tutorial for beginners Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates