About Me

My photo
Talk to me... you will know

Monday, August 29, 2011

Hibernate



The required jar files are
  • asm.jar
  • commons-collections-2.1.1.jar
  • commons-logging-1.0.4.jar
  • cglib-2.1.3.jar
  • dom4j-1.6.1.jar
  • ehcache-1.6.0-beta1.jar
  • hibernate3.jar
  • jta.jar

Put all the xml files in the source folder outside the created package.

Mention the class and default values properly

in the configuration to create session factory add the xml in case it is not detected directly.


SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();


 Also checkout the following example


Happy hibernating:)
//DataEntry.java
/*****************************************************************************
 * In this program we are trying to applying the one-to-many relationship in
 * both the ways.
 *     Concept:
 *     Trinaers can take multiple technologies
 *     A technology can be taken by multiple Trainers
 *
 * Through this application you can check how the logic works for one-to-many
 * in both ways but its not suitable for actual implementation because this
 * application creats two tables only - TRAINER and TECHNOLOGY.
 *
 *  After running this application you will found that there is problem with
 *  inserting of new record next time.
 *  To resolve this problem you can convert this application to many-to-many.
 *
 */


package ajo.hib;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;


import org.hibernate.*;
import org.hibernate.cfg.Configuration;


public class DataEntry {
    public static void main(String[] args)throws IOException {
        int i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("2.insert 3.delete 1.update\n Enter your choice: ");
        i=Integer.parseInt(br.readLine());
        Employee e= new Employee(); e.setEmpId("E102");
       
          EmployeeDAO ed= new EmployeeDAO();
       
        switch(i)
        {
      
        case 1:
          //for update
          ed.update(e);
          break;
       
        case 2:
        // for insert operation
        //Employee e = new Employee();
        e.setEmpId("E102");
        e.setEmpName("Mahesh");


        //EmployeeDAO ed = new EmployeeDAO();


        ed.insert(e);
        break;
        case 3:
            //for delete
         e.setEmpId("E102");
       
          EmployeeDAO eDAO= new EmployeeDAO();
       
          eDAO.delete(e);
         break;
         default:
             System.out.println("Invalid");
             break;
        }
    }
}

//EmployeeDAO.java
package ajo.hib;


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


public class EmployeeDAO implements IEmployeeDAO {


    public void insert(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
      
        ses.save(e);
        //e.setEmpName("rajeev"); // update statement gets fired for this
        tr.commit();


    }
  
    public void update(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
        e=(Employee) ses.load("ajo.hib.Employee", e.getEmpId());
      
        e.setEmpName("Ajo");
      
        System.out.println(e);
      
        ses.save(e);
        //ses.refresh(e);
        tr.commit();
        System.out.println(e);
    }
    public void delete(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
        e=(Employee) ses.load("ajo.hib.Employee", e.getEmpId());
        System.out.println(e);
        ses.delete(e);
        tr.commit();
        System.out.println(e);
    }
  
}
//IEmployeeDAO.java

package ajo.hib;


public interface IEmployeeDAO {


    public void update(Employee e);
    public void insert(Employee e);
    public void delete(Employee e);
}

//Employee.java

package ajo.hib;


public class Employee
{
    String empName;
    String empId;
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
  
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return " Employee ID : "+empId + " Name : "+empName;
    }
}

//employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//hibernate/hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="ajo.hib.Employee" table="empl">
        <id name="empId" column="EMPLOYEE_ID">
            <generator class="assigned"/>
        </id>
        <property name="empName"/>
    </class>
</hibernate-mapping>

//hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//hibernate/hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">admin1234</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

sorting using comparator and comparable



People have problem in sorting class objects


here is a way to do that


have attached some code for example


i think its self explanatory



public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, String name, int age) {
        // set values on attributes
    }
    // getters & setters
}


*************************************************


import java.util.*;

public class Util {
  
    public static List<Employee> getEmployees() {
      
        List<Employee> col = new ArrayList<Employee>();
      
        col.add(new Employee(5, "Frank", 28));
        col.add(new Employee(1, "Jorge", 19));
        col.add(new Employee(6, "Bill", 34));
        col.add(new Employee(3, "Michel", 10));
        col.add(new Employee(7, "Simpson", 8));
        col.add(new Employee(4, "Clerk",16 ));
        col.add(new Employee(8, "Lee", 40));
        col.add(new Employee(2, "Mark", 30));
      
        return col;
    }
}

**********************************************

public class Employee implements Comparable<Employee> {
    private int empId;
    private String name;
    private int age;
  
    /**
     * Compare a given Employee with this object.
     * If employee id of this object is
     * greater than the received object,
     * then this object is greater than the other.
     */
    public int compareTo(Employee o) {
        return this.empId - o.empId ;
    }
    ….
}

************************************************************


import java.util.*;

public class TestEmployeeSort {
  
    public static void main(String[] args) {   
        List coll = Util.getEmployees();
        Collections.sort(coll); // sort method
        printList(coll);
    }
  
    private static void printList(List<Employee> list) {
        System.out.println("EmpId\tName\tAge");
        for (Employee e: list) {
            System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
        }
    }
}








Here is another example... using your own custom sort method by implementing comparator and passing it along with your sort method

package compareExamples;

import java.io.*;
import java.util.*;
public class Laptop implements Comparable<Laptop> {

 // Implementing compareTo on custom objects!

 // Member elements
 String manufacturer;
 String color;
 String model;
 Laptop() {
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  
  try {
   System.out.print("Manufacturer: ");
   manufacturer = in.readLine();
   System.out.print("Model: ");
   model = in.readLine();
   System.out.println("Color: ");
   color = in.readLine();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 @Override
 public int compareTo(Laptop o) {
  String obj1_1 = manufacturer+" "+model+" "+color;
  String obj1_2 = manufacturer+" "+model;
  String obj2_1 = o.manufacturer+" "+o.model+" "+o.color;
  String obj2_2 = o.manufacturer+" "+o.model;
  if(manufacturer.equalsIgnoreCase(o.manufacturer)){
   if(model.equalsIgnoreCase(o.model)) {
    if(color.equalsIgnoreCase(o.color)) {
     return 0;
    }
    else
     return obj1_1.compareToIgnoreCase(obj2_1);
   }
   else 
    return obj1_2.compareToIgnoreCase(obj2_2);
   }
  else 
   return manufacturer.compareToIgnoreCase(o.manufacturer);
  
 }
 
 public static void main(String args[]) {
  Laptop a[] = new Laptop[5];
  for(int i=0;i<5;i++) {
   a[i] = new Laptop();
  }
  // Sorting with the help of the logic defined in compareTo method of the class Laptop
  Arrays.sort(a);
  for(Laptop b : a) {
   System.out.println(b.manufacturer+"\n"+b.model+"\n"+b.color+"\n\n");
  }
  
  System.out.println("********************************************");
  
  // Custom sorting with the help of the comparator defined in the class CompareLoptopByColor's compare method

  CompareLaptopByColor com = new CompareLaptopByColor();
  Arrays.sort(a,com);
  for(Laptop b : a) {
   System.out.println(b.manufacturer+"\n"+b.model+"\n"+b.color+"\n\n");
  }
 }
 
 
}

-------------------------- The custom comparator class-------------------------

package compareExamples;

import java.util.Comparator;

public class CompareLaptopByColor implements Comparator<Laptop> {

 @Override
 public int compare(Laptop arg0, Laptop arg1) {  
  return arg0.color.compareToIgnoreCase(arg1.color);
 }

}

jstl defination

  What are the difference between <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %> and the one without "rt"? Sometimes when I remove "rt" the JSP won't compile, what is the reason?






 Unless you are using a very old version of JSP (JSP 1.2 or 1.1 to be exact) you shouldn't be using either of those. Those are JSTL 1.0 URIs and are not suited to modern versions of JSP.



you can instead use <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> even this will work

collections redefined

set : doesnt allow duplicates

list : allows insertion & deletion easy

tree : sorting

hash : easy search

linking : maintains order of insertion

map : mapped name/value pairs



now for every collection just mmatch the keyword and properties to know what is used for what reason...


like hashset=== hash+set: doesnt allow3 duplicates and help in easy search..


enjoy adding and learning. :)

Unique Selector


for selecting a uniquely defined no for people : for eg to take questions for people in a quiz as such that adjascent people face different questions we put forth the following logic:

take range=total_no_of_questions;
prime[]={list of prime nos other than two equal to no of people attending the quiz};
pos= math.random*(the no of people attending)
my_random=prime[pos]
for(int i=1;i<=range;i++)
    {
        my_question=(my_random*i)%range+1;
system.out.println("my random quetion no is : "+my_question);       
  }





check out this logic and comment here...


;)
There was an error in this gadget