Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Sunday, 21 May 2017

Hibernate one to many mapping example using set

Hibernate one to many mapping example using set


In this tutorial we are going to understand how to use XML to map a one-to-many association between Java objects and database tables using Hibernate framework. We will create a sample Hibernate-based application to manage the following entity relationship:



  1. Creating sample database and tables
  2. Required Jars for project
  3. Coding Hibernate Model Classes
  4. Creating Hibernate Mapping Files
  5. Writing Hibernate Configuration File
  6. Coding a Test Program
  1.  Creating sample database and tables
   Execute the following script in MySQL Workbench’s SQL Editor to create a database                     
   called cartdb with two tables named cart and items:

create database cartdb;
use cartdb;
 
CREATE TABLE `cart` (
  `cart_id` int(11) NOT NULL AUTO_INCREMENT,
  `total` int(11) NOT NULL,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`cart_id`)
);
 
CREATE TABLE `items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
   `cart_id` int(11) NOT NULL,
  `item_id` int(11) NOT NULL,
  `item_total` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  
  PRIMARY KEY (`id`),
  KEY `fk_cart` (`cart_id`),
  CONSTRAINT `fk_cart` FOREIGN KEY (`cart_id`) REFERENCES `cart` (`cart_id`)
);


2. Required Jars for project

   
hibernate-core-4.2.2.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jboss-logging-3.1.0.GA.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
javassist-3.15.0-GA.jar

3. Coding hibernate model classes

Create two JavaBean-style classes Cart.java and Items.java to model the two tables cart and items, respectively.

File net\engineeernitesh\hibernate\Cart.java:

package net.engineeernitesh.hibernate;
 
import java.util.Set;
 
public class Cart {
 
    private long id;
    private long total;
    private String name;
 
    private Set<Items> items;
 
    public Category() {
    }
 
    public Category(Long total,String name) {
     this.total = total;
        this.name = name;
    }
 
    // getters and setters...
 
}


File net\engineeernitesh\hibernate\Items.java:

package net.engineeernitesh.hibernate;
 
public class Items {
    private long id;
    private Cart cart;
    private long item_id;
    private long item_total;
    private long quantity;
     
    public Items() {
    }
 
    public Items(Cart cart,Long item_id,Long item_total,Long quantity) {
        this.cart = cart;
        this.item_id = item_id;
        this.item_total = item_total;
        this.quantity = quantity;
    }
 
 
    // getters and setters...
 
}

4. Creating hibernate mapping files

Create two XML files Cart.hbm.xml and Items.hbm.xml to tell Hibernate how to map the JavaBean classes above with the database tables.

File net\engineeernitesh\hibernate\Cart.hbm.xml:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
    <class name="Cart" table="CART">
        <id name="id" column="CART_ID">
            <generator class="native"/>
        </id>
  <property name="total" column="TOTAL" />
        <property name="name" column="NAME" />
 
        <set name="items" inverse="true" cascade="all">
            <key column="CART_ID" not-null="true" />
            <one-to-many class="Items"/>
        </set>
    </class> 
</hibernate-mapping>


File net\engineeernitesh\hibernate\Items.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
    <class name="Items" table="ITEMS">
        <id name="id" column="ID">
            <generator class="native"/>
        </id>
  <many-to-one name="cart" class="Cart"
            column="CART_ID" not-null="true"/>
        <property name="item_id" column="ITEM_ID" />
        <property name="item_total" column="ITEM_TOTAL" />
        <property name="quantity" column="QUANTITY" />
                
    </class> 
</hibernate-mapping>

5. Writing Hibernate Configuration File

Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection details and the mapping files:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>       
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/cartdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">secret</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
     
    <mapping resource="net/codejava/hibernate/Cart.hbm.xml"/>
    <mapping resource="net/codejava/hibernate/Items.hbm.xml"/>
       
  </session-factory>
</hibernate-configuration>


6. Coding a Test Program

Following is code of the test program that persists some sample data:

package net.engineeernitesh.hibernate;
 
import java.util.HashSet;
import java.util.Set;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
 
/**
 *
 * This program demonstrates using Hibernate framework to manage a
 * bidirectional one-to-many association.
 * @author www.engineeernitesh.blogspot
 *
 */
public class CartManager {
 
    public static void main(String[] args) {
        // loads configuration and mappings
        Configuration configuration = new Configuration().configure();
        ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
        registry.applySettings(configuration.getProperties());
        ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
         
        // builds a session factory from the service registry
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
         
        // obtains the session
        Session session = sessionFactory.openSession();
        session.beginTransaction();
         
        Cart cart = new Cart(2,"Shopping");
         
        Items bag = new Items(cart,1,2,5);
  
        Items book = new Items(cart,2,4,5);
         
             
        Set<Items> items = new HashSet<Items>();
        items.add(bag);
        items.add(book);
                 
        cart.setItems(items);
         
        session.save(cart);
         
        session.getTransaction().commit();
        session.close();       
    }
}


Related Topics:



Saturday, 20 May 2017

How to use subquery in hibernate criteria

How to use subquery in hibernate criteria


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. From below example we will find all Cart which have Items quantity 5.


SQL Query : select * from Cart where Cart.cart_id in (
    select Items.cart_id from Items where Items.quantity = 5)

We can get same result by using DetachedCriteria in Criteria.

DetachedCriteria userSubquery = DetachedCriteria.forClass(Items.class, "items")
    // Filter the Subquery
    .add(Restrictions.eq(Items.quantity, 5))
    // SELECT the Cart Id  
    .setProjection(Projections.property("items.cart_id") );
And the main query:

Criteria query = session.createCriteria(Cart.class, "cart")
    .add(Subqueries.propertyIn("cart.cart_id", userSubquery) );