Sunday, January 12, 2014

Bulk Inserts Into jlhobbies and jlstudents table for testing the concepts

<?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)
/*
 * 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)
package hibex;

import java.util.HashSet;
import java.util.Set;
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 OneToManyMappingInsertion3 {
    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();
               
        int counter =1;
        for(int i =1;i<=10000;i++){
            //Create the Student Object
            StudentTo sts = new StudentTo();
                sts.setSfname("FirstName "+i);
                sts.setSlname("LastName "+i);
                sts.setSid(i);
                sts.setSbdate(new java.util.Date());
            //Generate Hobbies Objects and add it to set and
            //add it to student
            for(int j=1;j<=10;j++){
               
               HobbyTo hob = new HobbyTo();
               hob.setHobbyCategory("Category:"+j);
               hob.setHobbyName("Student: "+i+" Hobby:"+j);
               hob.setHobbyId(counter++);
               hob.setStudent(sts);
               sts.getHobbies().add(hob);
              
              
              
              
               
            }
            ses.save(sts);
           
           
           
        }
       
       
       
       
      
        //ses.save(hob1);
        tx.commit();
        }catch(Exception e ){
            tx.rollback();
            e.printStackTrace();
        }
       
       
       
    }
}

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();
        }
      
      
      
    }
}






























RetrievingAllStudentRecordsUsingHQLListAndIterate10

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 RetrievingAllStudentRecordsUsingHQLListAndIterate10 {
    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 ";
          
         
          
            Iterator it = null;
          
            it = ses.createQuery(allStudentHql).iterate();
            System.out.println("After iterate call ");
             while(it.hasNext()){
                StudentTo st = (StudentTo)it.next();
                System.out.println("StudentFirstName: "+st.getSfname()+" StudentLatName: "+st.getSlname());
              
              
            }
           
              System.out.println("Observe the output carefully with query.iterate "
                      + " One query to retrieve all student ids "
                      + " and n queries to retrieve the details "
                      + "Here n is the no of students ");
              System.out.println("If there are 3 students 1 query to retrieve just primary keys"
                      + "and 3 queries to retrieve student details ");     
                  
                        //Output
           //              Hibernate: select studentto0_.sid as col_0_0_ from jlstudents studentto0_
           //After Iterate Call
           //Hibernate: select studentto0_.sid as col_0_0_ from jlstudents studentto0_
           //Hibernate: select studentto0_.sid as sid0_0_, studentto0_.sbdate as sbdate0_0_, studentto0_.jlsfname as jlsfname0_0_, studentto0_.jlslname as jlslname0_0_ from jlstudents studentto0_ where studentto0_.sid=?
           //StudentFirstName: Anilkumar StudentLatName: Chintha
           //Hibernate: select studentto0_.sid as sid0_0_, studentto0_.sbdate as sbdate0_0_, studentto0_.jlsfname as jlsfname0_0_, studentto0_.jlslname as jlslname0_0_ from jlstudents studentto0_ where studentto0_.sid=?
           //StudentFirstName: Rishitha StudentLatName: Chintha
           //Hibernate: select studentto0_.sid as sid0_0_, studentto0_.sbdate as sbdate0_0_, studentto0_.jlsfname as jlsfname0_0_, studentto0_.jlslname as jlslname0_0_ from jlstudents studentto0_ where studentto0_.sid=?
           //StudentFirstName: Sunilkumar StudentLatName: Chintha
           //Hibernate: select studentto0_.sid as sid0_0_, studentto0_.sbdate as sbdate0_0_, studentto0_.jlsfname as jlsfname0_0_, studentto0_.jlslname as jlslname0_0_ from jlstudents studentto0_ where studentto0_.sid=?
           //StudentFirstName: FourthStudentFname StudentLatName: FourthStudentLname
           //Observe the output carefully with query.iterate  One query to retrieve all student ids  and n queries to retrieve the details Here n is the no of students
           //If there are 3 students 1 query to retrieve just primary keysand 3 queries to retrieve student details
           
           
           
         
           System.out.println("************* Using query.list method ");
         
            List stList = ses.createQuery(allStudentHql).list();
          
            Iterator its = stList.iterator();
            while(its.hasNext()){
                StudentTo st = (StudentTo)its.next();
                System.out.println("StudentFirstName: "+st.getSfname()+" StudentLatName: "+st.getSlname());
              
              
            }
            System.out.println("Observe the output carefully Only One select query is executed"
                    + "to get all the student details ");
//            ************* Using query.list method
//            Hibernate: select studentto0_.sid as sid0_, studentto0_.sbdate as sbdate0_, studentto0_.jlsfname as jlsfname0_, studentto0_.jlslname as jlslname0_ from jlstudents studentto0_
//            StudentFirstName: Anilkumar StudentLatName: Chintha
//            StudentFirstName: Rishitha StudentLatName: Chintha
//            StudentFirstName: Sunilkumar StudentLatName: Chintha
//            StudentFirstName: FourthStudentFname StudentLatName: FourthStudentLname
           
           
           
          
          
          
            tx.commit();
        }catch(Exception e ){
            tx.rollback();
            e.printStackTrace();
        }
      
      
      
    }
}


























How to Filter Records Using Criteria (Restrictions) 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.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.jl.vo.HobbyTo;
import org.jl.vo.StudentTo;

/**
 *
 * @author Rishitha
 */
public class HowToFilterStudentsUsingRestrictions9 {
    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();
            Criteria crit = ses.createCriteria(StudentTo.class);
            Criterion res = Restrictions.like("slname", "Chintha");
            crit.add(res);
            List stList = crit.list();
           
            Iterator it = stList.iterator();
            while(it.hasNext()){
                StudentTo st = (StudentTo)it.next();
                System.out.println("StudentFirstName: "+st.getSfname()+" StudentLatName: "+st.getSlname());
               
               
            }
           
            tx.commit();
        }catch(Exception e ){
            tx.rollback();
            e.printStackTrace();
        }
       
       
       
    }
}



















Hibernate One to Many example Using Annotations

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.Set;
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 OneToManyMappingInsertion3 {
    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();
        StudentTo st = (StudentTo)ses.get(StudentTo.class, 1);
      
        HobbyTo hob1 = new HobbyTo();
        hob1.setHobbyId(1);
        hob1.setHobbyName("Gardening");
        hob1.setHobbyCategory("Refreshment");
        hob1.setStudent(st);
        Set hobbies = new HashSet();
        hobbies.add(hob1);
        System.out.println(st.getHobbies());
        System.out.println("Hello 1");
        st.getHobbies().addAll(hobbies);
        System.out.println("Hello 2");
        ses.save(st);
        //ses.save(hob1);
        tx.commit();
        }catch(Exception e ){
            tx.rollback();
            e.printStackTrace();
        }
      
      
      
    }
}






















Thursday, January 9, 2014

Difference Between Get and Load in Hibernate

1)
package hibapp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Rishitha
 */
public class GetAndLoad {
   
   
    public static void main(String args[]){
       
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session ses = sf.openSession();
       
        //In Hibernate you can load object with
        //1)Load or 2)Get
       
       
       
        //Let Us First See Load Method...
        //and try to find an existing record
       
        PostTo st = (PostTo)ses.load(PostTo.class, new Long(1));
       
        System.out.println("Select query won't be fired by this time by the above"
                + " load method call");
         
        //At this step no select query will be executed in case
        //of Load,Hibernate creates a dummy object and just load
        //the primary key value.In this case it create a proxy
        //object which looks similar to PostTo and populates
        //the id with 1
       
        //When you call get on any non primary key property
        //Select query gets fired
        System.out.println("Now Select Query Fires because you have accessed "+
        "non primary key propert i.e getConent");
        String content = st.getContent();
       
        System.out.println("Post Content "+content);
       
       
        //Now we will try to load unexisting record
         PostTo unexPost = (PostTo)ses.load(PostTo.class, new Long(100));
         System.out.println("You might expect that above line throws exception "+
             "But as I said.. by that time... with out firing any select query "+
              "hibernate just returns proxy object with primary key set ");
        System.out.println("\n");
         System.out.println("After accessing getContent in the below you get the exception "+
         "because hibernate fires the select query now ");
        try{
           unexPost.getContent();
        }catch(Exception e ){
            System.out.println("Load throws exception when we try to load "
                    + "non existing object ");
        }
     
       
            
        //Now we will see Get
        //Get immediately fires the select query
        //If it doesn't find.. the record it will give null....
        ses=sf.openSession();
        System.out.println("\n");
        System.out.println("With Get hibernate fires select query  immediately unlike "
                + "Load which fires select only when... non primary key property"
                + "is accessed.Also you have to remember another important point get"
                + "first checks if the object you are trying to retrieve is in first level cache"
                + "that is session cache.. if that is not available then fires select query\n ");
        PostTo post = (PostTo)ses.get(PostTo.class, new Long(1));
        System.out.println("Conetent from Get "+post.getContent());
       
        System.out.println("\n Now I am trying to get the post 1 again but you observe"
                + " it won't fire select query again because in the above step post 1 is loaded and "
                + " it is already in session cache ");
        post =  (PostTo)ses.get(PostTo.class, new Long(1));
       
       
        System.out.println("\nTrying to get non existing object ");
        post = (PostTo)ses.get(PostTo.class,new Long(100));
        System.out.println("\nGet returns null and it doesn't throw exception like load method ");
       
   
    }
   
  
   
}












2)



<?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="hibapp.PostTo"/>  
  
  </session-factory>
</hibernate-configuration>





3)
package hibapp;

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

/**
 *
 * @author Rishitha
 */
@Entity
@Table(name="jlposts")
public class PostTo {
    @Id
    Long postId;
    String submittedBy;
    String content;
   
    public PostTo(){}

    public Long getPostId() {
        return postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public String getSubmittedBy() {
        return submittedBy;
    }

    public void setSubmittedBy(String submittedBy) {
        this.submittedBy = submittedBy;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
   
   
}


Assumption: Assume Only one record with post id 1 exists
insert into jlposts values(1,'Anil','TestContent');

Output:
---------
Select query won't be fired by this time by the above load method call
Now Select Query Fires because you have accessed non primary key propert i.e getConent
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Post Content Anil
You might expect that above line throws exception But as I said.. by that time... with out firing any select query hibernate just returns proxy object with primary key set


After accessing getContent in the below you get the exception because hibernate fires the select query now
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Load throws exception when we try to load non existing object


With Get hibernate fires select query  immediately unlike Load which fires select only when... non primary key propertyis accessed.Also you have to remember another important point hibernatefirst checks if the object you are trying to retrieve is in first level cachethat is session cache.. if that is not available then fires select query

Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?
Conetent from Get Anil

 Now I am trying to get the post 1 again but you observe it won't fire select query again because in the above step post 1 is loaded and  it is already in session cache

Trying to get non existing object
Hibernate: select postto0_.postId as postId0_0_, postto0_.content as content0_0_, postto0_.submittedBy as submitte3_0_0_ from jlposts postto0_ where postto0_.postId=?

Get returns null and it doesn't throw exception like load method 










Saturday, January 4, 2014

Spring AOP example Declarative Approach Using AOP namespace (Before Advice)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
">
  
    <bean id='msg' class="aopproj.MessageClass"></bean>
    <bean id='logging' class='aopproj.BeforeAdvice'></bean>
    <aop:config>
      
        <aop:aspect ref='logging'>
            <aop:before method='logBefore' pointcut="within (aopproj.MessageClass)"/>
          
        </aop:aspect>
      
      
      
      
    </aop:config>
  
  
</beans>

BeforeAdvice.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 aopproj;

/**
 *
 * @author Rishitha
 */
public class BeforeAdvice {
   
    public void logBefore(){
        System.out.println("log before ");
       
       
    }
   
}

MessageClass.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 aopproj;

/**
 *
 * @author Rishitha
 */
public class MessageClass {
   
   
    private String messageHeader="msgHeader";
    private String messageBody="msgBody";
   
    public MessageClass(){
       
    }

    public String getMessageHeader() {
        return messageHeader;
    }

    public void setMessageHeader(String messageHeader) {
        this.messageHeader = messageHeader;
    }

    public String getMessageBody() {
        return messageBody;
    }

    public void setMessageBody(String messageBody) {
        this.messageBody = messageBody;
    }
   
   
   
   
   
   
   
   
   
}




TestMain.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 aopproj;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Rishitha
 */
public class TestMain {
   
    public static void main(String args[]){
       
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-beans.xml");
        MessageClass msg = (MessageClass)ctx.getBean("msg");
       
        msg.getMessageBody();
       
       
    }
   
   
   
}

Jars Required:

Spring related jars
aop-alliance.jar
aspectj.jar
aspectjweaver.jar