Thursday, July 4, 2013

JPA 2.0 + Hibernate + MySQL + Spring + Log4j



JAVA PERSISTENCE API(JPA) 2.0, MySQL, HIBERNATE, SPRING, LOG4J

 

Code Structure in Eclipse :      
      





Jars Required:
 



AbstractEmployee.java

package com.sushil.jpa.model;
import javax.persistence.*;

@MappedSuperclass
public abstract class AbstractEmployee implements java.io.Serializable {

       private Integer empId;
       private Department department;
       private Long salary;

       public AbstractEmployee() {}

       public AbstractEmployee(Integer empId) {
              this.empId = empId;
       }

       public AbstractEmployee(Integer empId, Department department, Long salary) {
              this.empId = empId;
              this.department = department;
              this.salary = salary;
       }

       @Id
@Column(name ="emp_id", unique = true, nullable = false, insertable = true, updatable = true)
       public Integer getEmpId() {
              return this.empId;
       }

       public void setEmpId(Integer empId) {
              this.empId = empId;
       }

       @ManyToOne(cascade = {}, fetch = FetchType.LAZY)
       @JoinColumn(name = "dept_id", unique = false, nullable = true, insertable = true, updatable = true)
       public Department getDepartment() {
              return this.department;
       }

       public void setDepartment(Department department) {
              this.department = department;
       }

       @Column(name = "salary", unique = false, nullable = true, insertable = true, updatable = true, precision = 8, scale = 0)
       public Long getSalary() {
              return this.salary;
       }

       public void setSalary(Long salary) {
              this.salary = salary;
       }
}

AbstractDepartment.java

package com.sushil.jpa.model;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;

@MappedSuperclass
public abstract class AbstractDepartment implements java.io.Serializable {

       private Integer deptId;
       private String deptDesc;
       private Set<Employee> employees = new HashSet<Employee>(0);

       public AbstractDepartment() { }

       public AbstractDepartment(Integer deptId) {
              this.deptId = deptId;
       }

       public AbstractDepartment(Integer deptId, String deptDesc,
                     Set<Employee> employees) {
              this.deptId = deptId;
              this.deptDesc = deptDesc;
              this.employees = employees;
       }

       @Id
       @Column(name = "dept_id", unique = true, nullable = false, insertable = true, updatable = true)
       public Integer getDeptId() {
              return this.deptId;
       }

       public void setDeptId(Integer deptId) {
              this.deptId = deptId;
       }

       @Column(name = "dept_desc", unique = false, nullable = true, insertable = true, updatable = true, length = 100)
       public String getDeptDesc() {
              return this.deptDesc;
       }

       public void setDeptDesc(String deptDesc) {
              this.deptDesc = deptDesc;
       }

       @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "department")
       public Set<Employee> getEmployees() {
              return this.employees;
       }

       public void setEmployees(Set<Employee> employees) {
              this.employees = employees;
       }
}

Employee.java

package com.sushil.jpa.model;

import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee extends AbstractEmployee implements java.io.Serializable {

       public Employee() {  }
       public Employee(Integer empId) {
              super(empId);
       }
public Employee(Integer empId, Department department, Long salary) {
              super(empId, department, salary);
       }

}

Department.java 

package com.sushil.jpa.model;
import java.util.Set;
import javax.persistence.*;

@Entity
@Table(name = "department")
public class Department extends AbstractDepartment implements java.io.Serializable {

       public Department() {}

       public Department(Integer deptId) {
              super(deptId);
       }

    public Department(Integer deptId, String deptDesc, Set<Employee> employees) {
              super(deptId, deptDesc, employees);
       }
}

DepartmentDAO.java 

package com.sushil.jpa.DAO;
import java.util.*;
import com.sushil.jpa.model.Department;

public interface DepartmentDAO {

       public void save(Department entity);
       public void delete(Department entity);
       public Department update(Department entity);
       public Department findById(Integer id);
       public List<Department> findByProperty(String propertyName, Object value);
       public List<Department> findByDeptDesc(Object deptDesc);
       public List<Department> findAll();
}

EmployeeDAO.java

package com.sushil.jpa.DAO;
import java.util.List;
import com.sushil.jpa.model.Employee;

public interface EmployeeDAO {

       public void save(Employee entity);
       public void delete(Employee entity);
       public Employee update(Employee entity);
       public Employee findById(Integer id);
       public List<Employee> findByProperty(String propertyName, Object value);
       public List<Employee> findBySalary(Object salary);
       public List<Employee> findAll();
}

DepartmentDAOImpl.java

package com.sushil.jpa.DAO;

import java.util.*;
import javax.persistence.*;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import com.sushil.jpa.model.Department;

public class DepartmentDAOImpl extends JpaDaoSupport implements DepartmentDAO {

       // property constants
       public static final String DEPT_DESC = "deptDesc";

       public void save(Department entity) {
              logger.info("saving Department instance");
              try {
                     getJpaTemplate().persist(entity);
                     logger.info("save successful");
              } catch (RuntimeException re) {
                     logger.error("save failed", re);
                     throw re;
              }
       }

       public void delete(Department entity) {
              logger.info("deleting Department instance");
              System.out.println("in Dept DAO delete() and entity" + entity);
              try {
                    
                     entity = getJpaTemplate().getReference(Department.class, entity.getDeptId());
                     getJpaTemplate().remove(entity);
                     logger.info("delete successful");
              } catch (RuntimeException re) {
                     logger.error("delete failed", re);
                     throw re;
              }
       }

       public Department update(Department entity) {
              logger.info("updating Department instance");
              try {
                     Department result = getJpaTemplate().merge(entity);
                     logger.info("update successful");
                     return result;
              } catch (RuntimeException re) {
                     logger.error("update failed", re);
                     throw re;
              }
       }

       public Department findById(Integer id) {
              logger.info("finding Department instance with id: " + id);
              try {
                     Department instance = getJpaTemplate().find(Department.class, id);
                     return instance;
              } catch (RuntimeException re) {
                     logger.error("find failed", re);
                     throw re;
              }
       }

       @SuppressWarnings("unchecked")
       public List<Department> findByProperty(String propertyName, final Object value) {
              logger.info("finding Department instance with property: "+ propertyName + ", value: " + value);
              try {
                     final String queryString = "select model from Department model where model."
                                  + propertyName + "= :propertyValue";
                     return getJpaTemplate().executeFind(new JpaCallback() {
                           public Object doInJpa(EntityManager em)
                                         throws PersistenceException {
                                  Query query = em.createQuery(queryString);
                                  query.setParameter("propertyValue", value);
                                  return query.getResultList();
                           }
                     });
              } catch (RuntimeException re) {
                     logger.error("find by property name failed", re);
                     throw re;
              }
       }

       public List<Department> findByDeptDesc(Object deptDesc) {
              return findByProperty(DEPT_DESC, deptDesc);
       }

       @SuppressWarnings("unchecked")
       public List<Department> findAll() {
              logger.info("finding all Department instances");
              try {
                     final String queryString = "select model from Department model";
                     return getJpaTemplate().executeFind(new JpaCallback() {
                           public Object doInJpa(EntityManager em)
                                         throws PersistenceException {
                                  Query query = em.createQuery(queryString);
                                  return query.getResultList();
                           }
                     });
              } catch (RuntimeException re) {
                     logger.error("find all failed", re);
                     throw re;
              }
       }

       public static DepartmentDAO getFromApplicationContext(
                     ApplicationContext ctx) {
              return (DepartmentDAO) ctx.getBean("DepartmentDAO");
       }
}

EmployeeDAOImpl.java

package com.sushil.jpa.DAO;
import java.util.List;
import javax.persistence.*;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import com.sushil.jpa.model.Employee;

public class EmployeeDAOImpl extends JpaDaoSupport implements EmployeeDAO {

       public static final String SALARY = "salary";

       public void save(Employee entity) {
              logger.info("saving Employee instance");
              try {
                     getJpaTemplate().persist(entity);
                     logger.info("save successful");
              } catch (RuntimeException re) {
                     logger.error("save failed", re);
                     throw re;
              }
       }

       public void delete(Employee entity) {
              logger.info("deleting Employee instance");
              try {
                     entity = getJpaTemplate().getReference(Employee.class,
                                  entity.getEmpId());
                     getJpaTemplate().remove(entity);
                     logger.info("delete successful");
              } catch (RuntimeException re) {
                     logger.error("delete failed", re);
                     throw re;
              }
       }

       public Employee update(Employee entity) {
              logger.info("updating Employee instance");
              try {
                     Employee result = getJpaTemplate().merge(entity);
                     logger.info("update successful");
                     return result;
              } catch (RuntimeException re) {
                     logger.error("update failed", re);
                     throw re;
              }
       }

       public Employee findById(Integer id) {
              logger.info("finding Employee instance with id: " + id);
              try {
                     Employee instance = getJpaTemplate().find(Employee.class, id);
                     return instance;
              } catch (RuntimeException re) {
                     logger.error("find failed", re);
                     throw re;
              }
       }

       @SuppressWarnings("unchecked")
       public List<Employee> findByProperty(String propertyName, final Object value) {
              logger.info("finding Employee instance with property: " + propertyName
                           + ", value: " + value);
              try {
                     final String queryString = "select model from Employee model where model."
                                  + propertyName + "= :propertyValue";
                     return getJpaTemplate().executeFind(new JpaCallback() {
                           public Object doInJpa(EntityManager em)
                                         throws PersistenceException {
                                  Query query = em.createQuery(queryString);
                                  query.setParameter("propertyValue", value);
                                  return query.getResultList();
                           }
                     });
              } catch (RuntimeException re) {
                     logger.error("find by property name failed", re);
                     throw re;
              }
       }

       public List<Employee> findBySalary(Object salary) {
              return findByProperty(SALARY, salary);
       }

       @SuppressWarnings("unchecked")
       public List<Employee> findAll() {
              logger.info("finding all Employee instances");
              try {
                     final String queryString = "select model from Employee model";
                     return getJpaTemplate().executeFind(new JpaCallback() {
                           public Object doInJpa(EntityManager em)
                                         throws PersistenceException {
                                  Query query = em.createQuery(queryString);
                                  return query.getResultList();
                           }
                     });
              } catch (RuntimeException re) {
                     logger.error("find all failed", re);
                     throw re;
              }
       }

public static EmployeeDAO getFromApplicationContext(ApplicationContext ctx) {
              return (EmployeeDAO) ctx.getBean("EmployeeDAO");
       }
}

JPAServiceBean.java

package com.sushil.jpa.services;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.sushil.jpa.DAO.DepartmentDAOImpl;
import com.sushil.jpa.model.Department;

@Transactional
public class JPAServiceBean {
      
       @Autowired
       private DepartmentDAOImpl deptDao;
       public void save(Department dept){
              deptDao.save(dept);
       }
             
       public void update(Department dept){
              deptDao.update(dept);
       }     
      
       public void delete(Integer deptId){
              Department dept = deptDao.findById(deptId);
              deptDao.delete(dept);
       }
      
       public Department findById(Integer deptId){
              return deptDao.findById(deptId);
       }
      
       public List<Department> findAll(){
              return deptDao.findAll();
       }     
      
}

persistence.xml 

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
   
       <persistence-unit name="JPATestPU" transaction-type="RESOURCE_LOCAL">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <class>com.sushil.jpa.model.Department</class>
              <class>com.sushil.jpa.model.Employee</class>
              <class>com.sushil.jpa.model.AbstractDepartment</class>
              <class>com.sushil.jpa.model.AbstractEmployee</class>
              <properties>
                     <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
                     <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdb1" />
                     <property name="hibernate.connection.username" value="root" />
                     <property name="hibernate.connection.password" value="admin" />
                     <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
                     <property name="hibernate.hbm2ddl.auto" value="update"/>
            </properties>
       </persistence-unit>
</persistence>

applicationContext.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
  
       <context:annotation-config/>
      
       <!-- declare EntityManagerFactory -->
<bean d="entityManagerFactory"            class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
              <property name="persistenceUnitName" value="JPATestPU" />
       </bean>
      
       <!-- inject into JpaTransactionManager -->
       <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
              <property name="entityManagerFactory" ref="entityManagerFactory" />
       </bean>
      
       <!-- enable container-managed transactions -->
       <tx:annotation-driven transaction-manager="transactionManager" />

       <bean id="DepartmentDAO" class="com.sushil.jpa.DAO.DepartmentDAOImpl">
              <property name="entityManagerFactory" ref="entityManagerFactory" />
       </bean>
      
       <bean id="JPAServiceBean" class="com.sushil.jpa.services.JPAServiceBean"/>
      
       <bean id="EmployeeDAO" class="com.sushil.jpa.DAO.EmployeeDAOImpl">
              <property name="entityManagerFactory" ref="entityManagerFactory" />
       </bean>
      
      
</beans>

log4j.properties

log4j.category.ext=DEBUG,ext
log4j.appender.ext=org.apache.log4j.ConsoleAppender
log4j.appender.ext.layout=org.apache.log4j.PatternLayout
log4j.appender.ext.layout.ConversionPattern=%d %p %l - %m%n
l0g4j.rootLogger=ext

TestClient.java

import java.util.List;

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

import com.sushil.jpa.model.Department;
import com.sushil.jpa.services.JPAServiceBean;


public class TestClient {

       private static ApplicationContext contextnull;
       public static void main(String[] args) {
              contextnew ClassPathXmlApplicationContext("ApplicationContext.xml");
              TestClient test = new TestClient();
             
              /* CRUD Operations un comment each and start working */
             
              /*Creating department*/
             
              //     test.saveDept();   // commented intentionally
             
              /*Updating department*/
             
              //test.updateDept();   // commented intentionally
             
              /*Retrieving department*/
             
              test.findAll();  
             
              /*Deleting department*/
             
              //test.deleteDept();  // commented intentionally
             
             
              //test.findByDeptId();
             
             
       }
      
      
       public Object getService(String beanName){
              return context.getBean(beanName);
             
       }
      
       public void findAll(){
             
              JPAServiceBean service = (JPAServiceBean)getService("JPAServiceBean");

              List<Department> list = service.findAll();
              if(!list.isEmpty()){
                     for(int i=0; i<list.size(); i++){
                           Department dept = list.get(i);
                           System.out.println("id="+dept.getDeptId()+", name="+dept.getDeptDesc());
                     }
              }
       }
      
       public void findByDeptId(){
              JPAServiceBean service = (JPAServiceBean)getService("JPAServiceBean");
             
              Department dept = service.findById(3);
              System.out.println("id="+dept.getDeptId()+ ", name="+dept.getDeptDesc());
       }
      
       public void saveDept(){
              JPAServiceBean service = (JPAServiceBean)getService("JPAServiceBean");
             
              Department dept = new Department();
              dept.setDeptId(3);
              dept.setDeptDesc("PDM");
              service.save(dept);
       }
      
       public void updateDept(){
             
              JPAServiceBean service = (JPAServiceBean)getService("JPAServiceBean");
             
              Department dept = new Department();
              dept.setDeptId(3);
              dept.setDeptDesc("PDM II");
              service.update(dept);
       }
      
       public void deleteDept(){
              JPAServiceBean service = (JPAServiceBean)getService("JPAServiceBean");
             
              service.delete(3);
       }
}

Before running the client comment

test.findAll();  

and uncomment

test.saveDept();

Run the client, than comment 

test.saveDept() 

 and uncomment 

others one by one to test.

Thanks


No comments: