Saturday, January 11, 2014

Very Importnat N+1 Select Problem in Hibernate......

hibernate.cfg.xml
------------------
<?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>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="org.jl.vo.StudentTo"/>  
    <mapping class="org.jl.vo.HobbyTo"/>
   
  </session-factory>
</hibernate-configuration>


2)
HobbyTo.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.vo;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name="jlhobbies")
public class HobbyTo {
    @Id
    private int hobbyId;
    private String hobbyName;
    private String hobbyCategory;
    @ManyToOne
    @JoinColumn(name = "sid")
    private StudentTo student;

  
   
    public HobbyTo(){}

    public int getHobbyId() {
        return hobbyId;
    }

    public void setHobbyId(int hobbyId) {
        this.hobbyId = hobbyId;
    }

    public String getHobbyName() {
        return hobbyName;
    }

    public void setHobbyName(String hobbyName) {
        this.hobbyName = hobbyName;
    }

    public String getHobbyCategory() {
        return hobbyCategory;
    }

    public void setHobbyCategory(String hobbyCategory) {
        this.hobbyCategory = hobbyCategory;
    }
   
   
     public StudentTo getStudent() {
        return student;
    }

    public void setStudent(StudentTo student) {
        this.student = student;
    }
   
   
   
}



3)
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jl.vo;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name="jlstudents")
public class StudentTo {
    @Id
    private int sid;
    @Column(name="jlsfname")
    private String sfname;
    @Column(name="jlslname")
    private String slname;
    @Temporal(TemporalType.DATE)

    private Date   sbdate;

  
   
   
    @OneToMany(mappedBy="student",cascade = {javax.persistence.CascadeType.ALL}, orphanRemoval=true)
  
    private Set<HobbyTo> hobbies = new HashSet();
   
   
   
    public StudentTo(){
       
    }

    public Date getSbdate() {
        return sbdate;
    }

    public void setSbdate(Date sbdate) {
        this.sbdate = sbdate;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSfname() {
        return sfname;
    }

    public void setSfname(String sfname) {
        this.sfname = sfname;
    }

    public String getSlname() {
        return slname;
    }

    public void setSlname(String slname) {
        this.slname = slname;
    }

    public Set<HobbyTo> getHobbies() {
        return hobbies;
    }

    public void setHobbies(Set<HobbyTo> hobbies) {
        this.hobbies = hobbies;
    }
   
   
  
   
}


4)

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//drop table jlstudents;
//drop table jlcourses;
//
//select * from jlstudents;
//select * from jlhobbies;
//
//drop table jlhobbies;
//drop table jlstudents;
package hibex;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.jl.vo.HobbyTo;
import org.jl.vo.StudentTo;

/**
 *
 * @author Rishitha
 */
public class UnderstandingNPlusSelectProblem11 {
    public static void main(String args[]){
      
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
      
        //Session is very important
        //and using session we do every thing in hibernate.
        //Eg We can save,update,delete,load,get etc.........
        Session ses = sf.openSession();
        //Now let us see how to add the hobbies to student1
        Transaction tx = null;
        try{
            tx = ses.beginTransaction();
            String allStudentHql = "FROM StudentTo ";
            System.out.println("N queries get executed later while you "
                    + "are iterating... 1 query initally to "
                    + " get the student details.. and later "
                    + " n queries to fetch the associated hobby details\n ");
            List stList = ses.createQuery(allStudentHql).list();
            System.out.println("In your case n is: "+stList.size());
          
            Iterator it = stList.iterator();
            int  i =0;
            while(it.hasNext()){
                StudentTo st = (StudentTo)it.next();
                System.out.println("\nYour "+(++i)+" th query is being executed ");
                Set hobbies = st.getHobbies();
                Iterator hit = hobbies.iterator();
                System.out.println("Hobbies of Student "+st.getSfname() +" "+st.getSlname());
                      
                while(hit.hasNext()){
                    HobbyTo ht = (HobbyTo)hit.next();
                    System.out.println("Hobby "+ht.getHobbyName());
                  
                  
                }
              
              
            }
            System.out.println("\nYou can observe one query to get all the student details ");
            System.out.println("n queries to get hobbies ");
            System.out.println("n depends on the no of students ");
            System.out.println("This is called n+1 select problem ");
            System.out.println("This will cause performance problem because if there are huge no of "
                    + "records,it will genearte huge no of select queries "
                    + "\nThis is called lazy loading and it is by default "
                    + "\nYou can eagerly load using eager fetching this can be done"
                    + " with HQL or Criteria We will see in next examples ");
//            Hibernate: select studentto0_.sid as sid0_, studentto0_.sbdate as sbdate0_, studentto0_.jlsfname as jlsfname0_, studentto0_.jlslname as jlslname0_ from jlstudents studentto0_
//Hibernate: select hobbies0_.sid as sid0_1_, hobbies0_.hobbyId as hobbyId1_, hobbies0_.hobbyId as hobbyId1_0_, hobbies0_.hobbyCategory as hobbyCat2_1_0_, hobbies0_.hobbyName as hobbyName1_0_, hobbies0_.sid as sid1_0_ from jlhobbies hobbies0_ where hobbies0_.sid=?
//Hobbies of Student Anilkumar Chintha
//Hobby Gardening
//Hobby Playing
//Hibernate: select hobbies0_.sid as sid0_1_, hobbies0_.hobbyId as hobbyId1_, hobbies0_.hobbyId as hobbyId1_0_, hobbies0_.hobbyCategory as hobbyCat2_1_0_, hobbies0_.hobbyName as hobbyName1_0_, hobbies0_.sid as sid1_0_ from jlhobbies hobbies0_ where hobbies0_.sid=?
//Hobbies of Student Rishitha Chintha
//Hobby Growth
//Hobby Playing
//Hibernate: select hobbies0_.sid as sid0_1_, hobbies0_.hobbyId as hobbyId1_, hobbies0_.hobbyId as hobbyId1_0_, hobbies0_.hobbyCategory as hobbyCat2_1_0_, hobbies0_.hobbyName as hobbyName1_0_, hobbies0_.sid as sid1_0_ from jlhobbies hobbies0_ where hobbies0_.sid=?
//Hobbies of Student Sunilkumar Chintha
//Hibernate: select hobbies0_.sid as sid0_1_, hobbies0_.hobbyId as hobbyId1_, hobbies0_.hobbyId as hobbyId1_0_, hobbies0_.hobbyCategory as hobbyCat2_1_0_, hobbies0_.hobbyName as hobbyName1_0_, hobbies0_.sid as sid1_0_ from jlhobbies hobbies0_ where hobbies0_.sid=?
//Hobbies of Student FourthStudentFname FourthStudentLname
          
          
          
          
            tx.commit();
        }catch(Exception e ){
            tx.rollback();
            e.printStackTrace();
        }
      
      
      
    }
}






























No comments:

Post a Comment