Monday, 11 February 2013

Hibernate difference between get and load methods.



Primary difference between get and load is,

load():   
  1. It creates a proxy of that object using the given Id instead of fetching the row from the database. It works on the Lazy loading phenomenon, you will get the actual object once after you tries to get the object members. That’s why if you are using load() then be aware because out of the session boundary you won’t be able to get the other details of that object if details were not fetched with in the session boundary.  
  2. Throws ObjectNotFoundException if data is not found in first cache and second in DB.


        User user = (User) session.load(User.class, userID);


get():  return the real object, an object that represent the database row, not proxy. If no row found , it return null.
        User user = (User) session.get(User.class, userID);

How to sort an ArrayList

ArrayList can be sort using any of the to ways:
  1. By implementing the Comparable Interface
  2. By implementing the Comparator Interface. 
Comparable interface is implemented when we specify the sorting inside the class itself. This type of sorting is required in Wrapper classes. I have shown sorting implementation below for an Employee Object.

First we need to have an Object in place; for which we need to implement Sorting. This Object implements Comparable interface. We have to override compareTo(Object obj) here, just to defining the sorting rule.  Here I am implementing sorting basis of employeeName.
package classes;
public class Employee implements Comparable{
public Employee(Long empId, String empName){
this.empId =empId;
this.empName=empName;
}
private String empName;
private Long empId;
private String empAddress;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public boolean equals(Object o){
if (this == o ){
return true;
}
if (o instanceof Employee){
if(((Employee) o).getEmpId().equals(this.empId)){
return true;
}else{
return false;
}
}else{
return false;
}
}
public int hashCode(){
return empId.intValue();
}
public String toString(){
return empId+ "  " +empName;
}

       @Override
public int compareTo(Object obj) {
Employee emp = (Employee)obj;
return empName.compareTo(emp.getEmpName());
}
}


Now we can sort the List which contains employee Objects. The important part of the below class is Collections.sort(empList). Here we are using sort() method of Collections class. 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import classes.Employee;

public class ArrayListSorting {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Employee> empList= empList();
                Collections.sort(empList);
for(Employee emp:empList){
System.out.println("List Values are ::: "+emp.getEmpId());
System.out.println("List Values are ::: "+emp);
}
}
private static ArrayList<Employee> empList(){
ArrayList<Employee> listData = new ArrayList<Employee>(); 
listData.add(new Employee(new Long(4),"Forth"));
listData.add(new Employee(new Long(5),"Fift"));
listData.add(new Employee(new Long(6),"Six"));
listData.add(new Employee(new Long(1),"First"));
listData.add(new Employee(new Long(2),"Second"));
listData.add(new Employee(new Long(3),"Third"));
return listData;
}
}

OutPut is :

List Values are ::: 5  Fift
List Values are ::: 1  First
List Values are ::: 4  Forth
List Values are ::: 2  Second
List Values are ::: 6  Six
List Values are ::: 3  Third


Comparator interface is required to be implemented where we can not touch the class and class has not implemented Comparable interface. Below are the steps we have to follow to achieve the sorting.

First we have to have create a class which does not implement Comparable Interface

package classes;

public class Employee {
public Employee(Long empId, String empName){
this.empId =empId;
this.empName=empName;
}

private String empName;
private Long empId;
private String empAddress;

public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Long getEmpId() {
return empId;
}
public void setEmpId(Long empId) {
this.empId = empId;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}

public boolean equals(Object o){

if (this == o ){
return true;
}
if (o instanceof Employee){
if(((Employee) o).getEmpId().equals(this.empId)){
return true;
}else{
return false;
}
}else{
return false;
}
}

public int hashCode(){
return empId.intValue();
}

public String toString(){

return empId+ "  " +empName;
}
}

Now the backbone of this way of sorting is required to be implement that's a class which implements Comparator interface.


package collections;
import java.util.Comparator;
import classes.Employee;

public class EmployeeComparator implements Comparator<Employee>{
@Override
public int compare(Employee emp1, Employee emp2) {
return (emp1.getEmpName()).compareTo(emp2.getEmpName());
        }
}

Here we are sorting List which contains Employee Objects.


package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import classes.Employee;

public class ArrayListSorting {

public static void main(String[] args) {

EmployeeComparator eComp = new EmployeeComparator();

List<Employee> empList= empList();
Collections.sort(empList, eComp);

for(Employee emp:empList){
System.out.println("List Values are ::: "+emp);
}
}
private static ArrayList<Employee> empList(){
ArrayList<Employee> listData = new ArrayList<Employee>();

listData.add(new Employee(new Long(4),"Forth"));
listData.add(new Employee(new Long(5),"Fift"));
listData.add(new Employee(new Long(6),"Six"));
listData.add(new Employee(new Long(1),"First"));
listData.add(new Employee(new Long(2),"Second"));
listData.add(new Employee(new Long(3),"Third"));

return listData;
}
}


OutPut is :

List Values are ::: 5  Fift
List Values are ::: 1  First
List Values are ::: 4  Forth
List Values are ::: 2  Second
List Values are ::: 6  Six
List Values are ::: 3  Third



Integrate Hibernate with Spring


4 simple steps to Integrate Hibernate with Spring
Step 1: Add the entries in spring-context.xml
<bean id="DS" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/webusers"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
</bean>

<context:component-scan base-package="com.hib.javabeam" />

<tx:annotation-driven transaction-manager="transactionManager" />
      
Step 2: Create a class which will serve you Session Factory
package com.hib.javabeam.utils.hibernate;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.dialect.MySQL5Dialect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

import com.hib.javabeam.domain.CustomerDetails;
import com.hib.javabeam.domain.Item;
import com.hib.javabeam.domain.Order;

@Configuration
public class HibernateConfiguration {

   @Value("#{DS}")
   private DataSource dataSource;

   @Bean
   public AnnotationSessionFactoryBean sessionFactoryBean() {
          Properties props = new Properties();
          props.put("hibernate.dialect",MySQL5Dialect.class.getName());
          props.put("hibernate.format_sql", "true");

          AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
          bean.setAnnotatedClasses(new Class[]{Item.class, Order.class, CustomerDetails.class});     
          bean.setHibernateProperties(props);
          bean.setDataSource(dataSource);
          bean.setSchemaUpdate(true);
          return bean;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
          return new HibernateTransactionManager( sessionFactoryBean().getObject() );
   }

}
Step 3: Create a DAO interface
package com.hib.javabeam.dao.api;

import com.hib.javabeam.domain.CustomerDetails;

public interface CustomerDetailsDAO {
      
       public void addCustomerDetails(CustomerDetails custDetails);

}


Step 4 : Implements DAO interface and perform the your operations
package com.hib.javabeam.dao.impl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hib.javabeam.dao.api.CustomerDetailsDAO;
import com.hib.javabeam.domain.CustomerDetails;

@Repository("cusomerDetailsDAO")
public class CustomerDetailsDAOImpl implements CustomerDetailsDAO {

       @Autowired
       SessionFactory sessionfactory;
      
       @Transactional
       public void addCustomerDetails(CustomerDetails custDetails) {
              sessionfactory.getCurrentSession().save(custDetails);
       }

}