• RubyonRails
  • Servlet
  • Struts
  • JSP
  • Java IO
  • Spring
  • SQL Tutorial
  • Core Java
  • JavaScript

  • <

    Hibernate one-to-Many Mapping


    one to many mapping means that one row in a table can be mapped to multiple rows in another table. For example, think of a Cart system where we have another table for Items. A cart can have multiple items, so here we have one to many mapping.

    Example



    Sql file
    
    CREATE TABLE `Cart` ( 
      `cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
      `total` decimal(10,0) NOT NULL, 
      `name` varchar(10) DEFAULT NULL, 
      PRIMARY KEY (`cart_id`) 
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
     
    CREATE TABLE `Items` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
      `cart_id` int(11) unsigned NOT NULL, 
      `item_id` varchar(10) NOT NULL, 
      `item_total` decimal(10,0) NOT NULL, 
      `quantity` int(3) NOT NULL, 
      PRIMARY KEY (`id`), 
      KEY `cart_id` (`cart_id`), 
      CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`) 
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; 
    

    Hibernate Maven Dependencies



    <project xmlns="http://maven.apache.org/POM/4.0.0" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
     http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
      <modelVersion>4.0.0</modelVersion> 
      <groupId>com.journaldev.hibernate</groupId> 
      <artifactId>HibernateOneToManyMapping</artifactId> 
      <version>0.0.1-SNAPSHOT</version> 
       
      <dependencies> 
      	<dependency> 
      		<groupId>org.hibernate</groupId> 
      		<artifactId>hibernate-core</artifactId> 
      		<version>4.3.5.Final</version> 
      	</dependency> 
      	<dependency> 
      		<groupId>mysql</groupId> 
      		<artifactId>mysql-connector-java</artifactId> 
      		<version>5.0.5</version> 
      	</dependency> 
      </dependencies> 
    
      
    </project>
    


    Model Classes


    Cart.java
    
    package com.tutorial.hibernate.model; 
     
    import java.util.Set; 
     
    public class Cart { 
     
    	private long id; 
    	private double total; 
    	private String name; 
    	private Set items; 
    	 
    	public long getId() { 
    		return id; 
    	} 
    	public void setId(long id) { 
    		this.id = id; 
    	} 
    	public double getTotal() { 
    		return total; 
    	} 
    	public void setTotal(double total) { 
    		this.total = total; 
    	} 
    	public String getName() { 
    		return name; 
    	} 
    	public void setName(String name) { 
    		this.name = name;
    	}
    	public Set getItems() { 
    		return items; 
    	} 
    	public void setItems(Set items) { 
    		this.items = items;
    	} 
    	 } 
    

    Items.java

    
    package com.tutorial.hibernate.model; 
     
    public class Items { 
     
    	private long id; 
    	private String itemId; 
    	private double itemTotal; 
    	private int quantity; 
    	private Cart cart; 
    	 
    	//Hibernate requires no-args constructor 
    	public Items(){} 
    	 
    	public Items(String itemId, double total, int qty, Cart c){ 
    		this.itemId=itemId; 
    		this.itemTotal=total; 
    		this.quantity=qty; 
    		this.cart=c; 
    	} 
    	public String getItemId() { 
    		return itemId; 
    	} 
    	public void setItemId(String itemId) { 
    		this.itemId = itemId; 
    	} 
    	public double getItemTotal() { 
    		return itemTotal; 
    	} 
    	public void setItemTotal(double itemTotal) {
    		this.itemTotal = itemTotal; 
    	} 
    	public int getQuantity() { 
    		return quantity; 
    	} 
    	public void setQuantity(int quantity) { 
    		this.quantity = quantity; 
    	}
    	public Cart getCart() { 
    		return cart; 
    	} 
    	public void setCart(Cart cart) { 
    		this.cart = cart; 
    	} 
    	public long getId() { 
    		return id; 
    	} 
    	public void setId(long id) { 
    		this.id = id; 
    	} 
    
    	}
    


    HibernateUtil.java

    
    package com.tutorial.hibernate.util; 
     
    import org.hibernate.SessionFactory; 
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
    import org.hibernate.cfg.Configuration; 
    import org.hibernate.service.ServiceRegistry; 
     
    public class HibernateUtil { 
     
    	private static SessionFactory sessionFactory; 
    	 
    	private static SessionFactory buildSessionFactory() { 
            try { 
                // Create the SessionFactory from hibernate.cfg.xml 
            	Configuration configuration = new Configuration(); 
            	configuration.configure("hibernate.cfg.xml"); 
            	System.out.println("Hibernate Configuration loaded"); 
            	 
            	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 
            	System.out.println("Hibernate serviceRegistry created"); 
            	 
            	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); 
            	 
                return sessionFactory; 
            } 
            catch (Throwable ex) {
                System.err.println("Initial SessionFactory creation failed." + ex); 
                ex.printStackTrace();
                throw new ExceptionInInitializerError(ex); 
            } 
        } 
    	 
    	public static SessionFactory getSessionFactory() { 
    		if(sessionFactory == null) sessionFactory = buildSessionFactory(); 
            return sessionFactory; 
        } 
    }
    
    

    hibernate.cfg.xml

    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
    		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    		"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.password">pankaj123</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
            <property name="hibernate.connection.username">pankaj</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            
            <property name="hibernate.current_session_context_class">thread</property>
            <property name="hibernate.show_sql">true</property>
            
            <mapping resource="cart.hbm.xml"/>
            <mapping resource="items.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    
    

    cart.hbm.xml

    
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    	"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    	
    <hibernate-mapping package="com.journaldev.hibernate.model">
    	<class name="Cart" table="CART" >
    		<id name="id" type="long">
    			<column name="cart_id" />
    			<generator class="identity" />
    		</id>
    		<property name="total" type="double">
    			<column name="total" />
    		</property>
    		<property name="name" type="string">
    			<column name="name" />
    		</property>
    		<set name="items" table="ITEMS" fetch="select">
    			<key>
    				<column name="cart_id" not-null="true"></column>
    			</key>
    			<one-to-many class="Items"/>
    		</set>
    	</class>
    	
    </hibernate-mapping>
    


    items.hbm.xml

    
    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
    
    <hibernate-mapping package="com.journaldev.hibernate.model">
    
    	<class name="Items" table="ITEMS">
    		<id name="id" type="long">
    			<column name="id" />
    			<generator class="identity" />
    		</id>
    		<property name="itemId" type="string">
    			<column name="item_id"></column>
    		</property>
    		<property name="itemTotal" type="double">
    			<column name="item_total"></column>
    		</property>
    		<property name="quantity" type="integer">
    			<column name="quantity"></column>
    		</property>
    		
    		<many-to-one name="cart" class="Cart">
    			<column name="cart_id" not-null="true"></column>
    		</many-to-one>
    	</class>
    
    </hibernate-mapping>
    
    
    
    
    

    One To Many Test



    package com.tutorial.hibernate.main; 
     
    import java.util.HashSet; 
    import java.util.Set; 
     
    import org.hibernate.Session; 
    import org.hibernate.SessionFactory; 
    import org.hibernate.Transaction; 
    
    import com.journaldev.hibernate.model.Cart;
    import com.journaldev.hibernate.model.Items;
    import com.journaldev.hibernate.util.HibernateUtil;
    
    public class HibernateOneToManyMain {
    
    	public static void main(String[] args) {
    
    		Cart cart = new Cart();
    		cart.setName("MyCart");
    		
    		Items item1 = new Items("I1", 10, 1, cart);
    		Items item2 = new Items("I2", 20, 2, cart);
    		Set itemsSet = new HashSet();
    		itemsSet.add(item1); itemsSet.add(item2);
    		
    		cart.setItems(itemsSet);
    		cart.setTotal(10*1 + 20*2);
    		
    		SessionFactory sessionFactory = null;
    		Session session = null;
    		Transaction tx = null;
    		try{
    		//Get Session
    		sessionFactory = HibernateUtil.getSessionFactory();
    		session = sessionFactory.getCurrentSession();
    		System.out.println("Session created");
    		//start transaction
    		tx = session.beginTransaction();
    		
    		//Save the Model objects
    		session.save(cart);
    		session.save(item1);
    		session.save(item2);
    		
    		//Commit transaction
    		tx.commit();
    		System.out.println("Cart ID="+cart.getId());
    		
    		}catch(Exception e){
    			System.out.println("Exception occured. "+e.getMessage());
    			e.printStackTrace();
    		}finally{
    			if(!sessionFactory.isClosed()){
    				System.out.println("Closing SessionFactory");
    				sessionFactory.close();
    			}
    		}
    	}
    
    }
    

    OUTPUT:



    Hibernate Configuration loaded
    Hibernate serviceRegistry created
    Session created
    Hibernate: insert into CART (total, name) values (?, ?)
    Hibernate: insert into ITEMS (item_id, item_total, quantity, cart_id) values (?, ?, ?, ?)
    Hibernate: insert into ITEMS (item_id, item_total, quantity, cart_id) values (?, ?, ?, ?)
    Hibernate: update ITEMS set cart_id=? where id=?
    Hibernate: update ITEMS set cart_id=? where id=?

    Cart ID=6
    Closing SessionFactory










    © copyright 2017-2021 Completedone pvt ltd.