Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Hibernate: Simple Example

Hibernate is a powerful ORM tool which makes developers life very easy. As we all read that Hibernate comes with its own session and transaction management features and also as a Java developer its not mandatory to have SQL knowledge. In below example we are going to see simple example with Employee class where we used to do operations like Create, Update, Read and Delete (CURD). For demo purpose we use MySQL connector and Hibernate 3 version.
Hibernate - Simple Example.png


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>com.app.hiber</groupId>
 <artifactId>hibernatesample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>Hibernate Sample</name>
 <description>Hibernate sample application</description>

 <dependencies>

  <!-- MySQL database driver -->

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.9</version>
   </dependency>

  <!-- Hibernate framework -->

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

  <dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
  </dependency>
 </dependencies>

 <properties>
  <java.version>1.6</java.version>  
 </properties>

</project>


hibernate.cfg.xml
<?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 -->
   <!--  Mysql Setting -->
   <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/roboticapp</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
   
   <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
  
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.app.hiber.models.Employee"/>
        
        
    </session-factory>

</hibernate-configuration>


Employee.java
package com.app.hiber.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="employee")
public class Employee {

 @Id 
 private int id;
 
 @Column(name="empname")
 private String empName;
 
 @Column(name="designation")
 private String designation;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 } 
}


DBCon.java
package com.app.hiber.dao;

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


public class DBCon {
 
 private static SessionFactory factory = null;
 
 private DBCon(){}
 
 public static SessionFactory getSessionFactory(){
  synchronized (DBCon.class) {
   if(factory == null){
    factory=new Configuration().configure().buildSessionFactory();    
   }
  }  
  return factory;
 }
}


EmpService.java
package com.app.hiber.dao;

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

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.app.hiber.models.Employee;

public class EmpService {
 
 private SessionFactory factory = null;
 
 public EmpService() {
  this.factory = DBCon.getSessionFactory();
 }
 
 public void addEmployee(Employee emp){
  Session session = null;
  try{
   session = factory.openSession();
   session.beginTransaction();
   
   session.save(emp);
   
   session.getTransaction().commit();

  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }  
 }
 
 public void updateEmployee(String name, int id){
  
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "UPDATE Employee SET empName = :name WHERE id = :id";
   
   Query query = session.createQuery(hql);
   query.setParameter("name", name);
   query.setParameter("id", id);
   
   int result = query.executeUpdate();
   session.getTransaction().commit();
 
   System.out.println("Rows affected : " + result);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
 }
 
 
 @SuppressWarnings("unchecked")
 public List<Employee> readEmployee(int id){
  List<Employee> list = new ArrayList<Employee>();
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "FROM Employee WHERE id = "+id;
   
   Query query = session.createQuery(hql);
   
   list = query.list();
 
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
  return list;
 }
 
 public void deleteEmployee(int id){
  
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "DELETE FROM Employee WHERE id = :id";
   
   Query query = session.createQuery(hql);
   query.setParameter("id", id);
   
   int result = query.executeUpdate();
   session.getTransaction().commit();
 
   System.out.println("Rows affected : " + result);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
 }
}


DemoTest.java
package com.app.hiber;

import java.util.List;

import com.app.hiber.dao.EmpService;
import com.app.hiber.models.Employee;

public class DemoTest {

 public static void main(String[] args) {
  
  Employee emp = new Employee();
  emp.setId(1000);
  emp.setEmpName("James");
  emp.setDesignation("CEO");
  
  //Create
  EmpService eSer = new EmpService();
  eSer.addEmployee(emp);
  
  //Update 
  eSer.updateEmployee("James 007", 1000);
  
  //Read
  List<Employee> list = eSer.readEmployee(1000);
  System.out.println(list.get(0).getEmpName());
  
  
  //Delete
  eSer.deleteEmployee(1000);
  
 }
}

Hibernate: Simple Example

Sample project can be download from this link.

Spring with Hibernate simple example using Injection

We all know that Spring framework is a widely used framework along with popular ORM tool Hibernate. IN this tutorial lets see simple Spring example with Hibernate integration using Injection. Here we used Spring 4 integrate with Hibernate 4 with annotation based for demonstration. Best thing here we can use old version Hibernate 3 also by both xml and annotation based.  Just need to make sure that pom.xml and spring.xml are properly edited. 
Spring with Hibernate simple example using Injection


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.app.sphiber</groupId>
 <artifactId>springhibernate</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>spring hibernate</name>

 <properties>
  <java.version>1.6</java.version>
  <spring-framework.version>4.0.3.RELEASE</spring-framework.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <logback.version>1.0.13</logback.version>
  <slf4j.version>1.7.5</slf4j.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring-framework.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring-framework.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>${spring-framework.version}</version>
  </dependency>

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${hibernate.version}</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>${hibernate.version}</version>
  </dependency>

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.9</version>
  </dependency>
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>1.4</version>
  </dependency>
  
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${slf4j.version}</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>${logback.version}</version>
   <scope>runtime</scope>
  </dependency>
 </dependencies>
 
 <build>
  <finalName>springhibernate</finalName>  
 </build>

</project>




spring.xml

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/roboticapp" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>


 <bean id="hibernateSessionFac"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.app.sphiber.model.Employee</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.format_sql">false</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>

 
 <bean id="empDao" class="com.app.sphiber.dao.EmpDaoImpl">
  <property name="sessionFactory" ref="hibernateSessionFac" />
 </bean>
</beans>




Employee.java

package com.app.sphiber.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="employee")
public class Employee {

 @Id 
 private int id;
 
 @Column(name="empname")
 private String empName;
 
 @Column(name="designation")
 private String designation;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 } 
}




EmpDao.java

package com.app.sphiber.dao;

import java.util.List;

import com.app.sphiber.model.Employee;

public interface EmpDao {

 public List<Employee> findByUserName(String empName);
 
 public List<Employee> getAllEmployees();
 
 public void save(Employee emp);
}




EmpDaoImpl.java

package com.app.sphiber.dao;

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

import com.app.sphiber.model.Employee;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class EmpDaoImpl implements EmpDao{
 
 private SessionFactory sessionFactory;
 
 @Autowired
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }
 
 
 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> findByUserName(String empName) {
  
  List<Employee> emp = new ArrayList<Employee>();
  Session session = null;
  session = this.sessionFactory.openSession();
  session.beginTransaction();  
  String qry = "from Employee where empName = '"+empName+"'";
  Query query = session.createQuery(qry);
  emp = query.list();
  session.close();
  
  return emp;

 }
 
 @Override
 public void save(Employee emp) {
  Session session = null;
  session = sessionFactory.openSession();
  session.beginTransaction();
  session.save(emp);
  session.getTransaction().commit();
  session.close();  
 }

 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> getAllEmployees() {
  List<Employee> emp = new ArrayList<Employee>();
  Session session = null;
  session = this.sessionFactory.openSession();
  session.beginTransaction();  
  String qry = "from Employee";
  Query query = session.createQuery(qry);
  emp = query.list();
  session.close();
  
  return emp;
 }
}




MyTestClass.java

package com.app.sphiber;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.sphiber.dao.EmpDao;
import com.app.sphiber.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");

  EmpDao dao = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee();
  emp.setId(10);
  emp.setEmpName("Steve");
  emp.setDesignation("COO");
  dao.save(emp);
  
  List<Employee> list = new ArrayList<Employee>();
  list = dao.findByUserName("Steve");
  for (Employee employee : list) {
   System.out.println("DESIGNATION : "+ employee.getDesignation());
  }
  
  
  List<Employee> list1 = new ArrayList<Employee>();
  list1 = dao.getAllEmployees();
  for (Employee employee : list1) {
   System.out.println("EMP NAME : "+ employee.getDesignation());
  }
  
  
  appContext.close();
 }
}




Spring with Hibernate simple example using Injection

Also you can download complete project code in this link.