Monday, 24 October 2016

2. Hibernate Spring More Operations

In previous tutorial, we have seen how to integrate hibernate with Spring and perform few of operations like creating entity and getting particular entity.

Now, we will extend that tutorial and will look how to perform more operations like fetching all entities , fetching all matching entities from database.

First, we need to add these new methods in DAO interface as below,
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package in.blogspot.ashish4java.employeesystem.dao;

import java.util.List;

import in.blogspot.ashish4java.employeesystem.model.Employee;

public interface EmployeeDao {

 void createEmployee(Employee emp);

 void updateEmployee(Employee emp);

 void deleteEmployee(Employee emp);

 Employee getEmployee(int employeeId);

 List<Employee> findAllEmployees();

 List<Employee> findAllEmployeesByDesignation(String designation);

}

Implement both these methods one by one.
Implementation of findAllEmployees() method will be like below,
1
2
3
4
5
6
7
 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> findAllEmployees() {
  Session session = getsession();
  Criteria criteria = session.createCriteria(Employee.class);
  return (List<Employee>) criteria.list();
 }

We have used hibernate Criteria object to fetch all records from database table. We did something similar in previous tutorial as well.

Implementation of findAllEmployeesByDesignation(String designation) method will be like below,
1
2
3
4
5
6
7
8
 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> findAllEmployeesByDesignation(String designation) {
  Session session = getsession();
  Query query = session.createQuery("from Employee where designation = :designation");
  query.setString("designation", designation);
  return query.list();
 }

In this implementation, we have used Hibernate Query Language (HQL) by creating Query object and passing required parameter in where clause. HQL is very similar to SQL however it has benefit that HQL is database independent so even if database type changes, there won't be much changes needed in DAO classes. Hibernate uses dialect defined to convert HQL to database specific query.

Now, let's update Service interface and implementation class for calling these operations.

EmployeeService.java
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package in.blogspot.ashish4java.employeesystem.service;

import java.util.List;

import in.blogspot.ashish4java.employeesystem.model.Employee;

public interface EmployeeService {

 void createEmployee(Employee emp);

 void updateEmployee(Employee emp);

 void deleteEmployee(Employee emp);

 Employee getEmployee(int employeeId);

 List<Employee> findAllEmployees();

 List<Employee> findAllEmployeesByDesignation(String designation);

}

EmployeeServiceImpl.java
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package in.blogspot.ashish4java.employeesystem.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import in.blogspot.ashish4java.employeesystem.dao.EmployeeDao;
import in.blogspot.ashish4java.employeesystem.model.Employee;

@Service ("empService")
public class EmployeeServiceImpl implements EmployeeService {

 @Autowired
 EmployeeDao employeeDao;

 @Override
 public void createEmployee(Employee emp) {
  employeeDao.createEmployee(emp);

 }

 @Override
 public void updateEmployee(Employee emp) {
  employeeDao.updateEmployee(emp);
 }

 @Override
 public void deleteEmployee(Employee emp) {
  employeeDao.deleteEmployee(emp);
 }

 @Override
 public Employee getEmployee(int employeeId) {
  return employeeDao.getEmployee(employeeId);
 }

 @Override
 public List<Employee> findAllEmployees() {
  return employeeDao.findAllEmployees();
 }

 @Override
 public List<Employee> findAllEmployeesByDesignation(String designation) {
  return employeeDao.findAllEmployeesByDesignation(designation);
 }

}

Updated client to demonstrate this is as below,

MainClient.java
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package in.blogspot.ashish4java.employeesystem.client;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import in.blogspot.ashish4java.employeesystem.model.Employee;
import in.blogspot.ashish4java.employeesystem.service.EmployeeService;
import in.blogspot.ashish4java.employeesystem.utils.EmployeeHelper;

public class MainClient {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  EmployeeHelper empHelper = (EmployeeHelper) context.getBean("empHelper");

  EmployeeService service = (EmployeeService) context.getBean("empService");

  for (int i = 1; i < 4; i++) {
   // Cretae Employee
   service.createEmployee(empHelper.CreateEmployeeOnRequest());
  }

  // Get All Employees Details
  List<Employee> employeesList = service.findAllEmployees();

  System.out.println();
  for (Employee employee : employeesList) {
   System.out.println(employee);
  }

  // Get All Employees with designation
  List<Employee> emplList = service.findAllEmployeesByDesignation("Full Stack Java developer");

  System.out.println();
  for (Employee employee : emplList) {
   System.out.println(employee);
  }
  context.close();
 }
}

Output

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: 
    drop table EMPLOYEE cascade
Hibernate: 
    drop sequence hibernate_sequence
Hibernate: 
    create table EMPLOYEE (
        employeeId int4 not null,
        designation varchar(255),
        firstName varchar(255),
        joiningDate timestamp,
        lastName varchar(255),
        leavingDate timestamp,
        primary key (employeeId)
    )
Hibernate: 
    create sequence hibernate_sequence
Oct 24, 2016 10:49:08 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: 
    select
        nextval ('hibernate_sequence')
Hibernate: 
    insert 
    into
        EMPLOYEE
        (designation, firstName, joiningDate, lastName, leavingDate, employeeId) 
    values
        (?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        nextval ('hibernate_sequence')
Hibernate: 
    insert 
    into
        EMPLOYEE
        (designation, firstName, joiningDate, lastName, leavingDate, employeeId) 
    values
        (?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        nextval ('hibernate_sequence')
Hibernate: 
    insert 
    into
        EMPLOYEE
        (designation, firstName, joiningDate, lastName, leavingDate, employeeId) 
    values
        (?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        this_.employeeId as employee1_0_0_,
        this_.designation as designat2_0_0_,
        this_.firstName as firstNam3_0_0_,
        this_.joiningDate as joiningD4_0_0_,
        this_.lastName as lastName5_0_0_,
        this_.leavingDate as leavingD6_0_0_ 
    from
        EMPLOYEE this_

Employee [firstName=ABC98, lastName=XYZ18, employeeId=1, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Employee [firstName=ABC73, lastName=XYZ75, employeeId=2, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Employee [firstName=ABC13, lastName=XYZ61, employeeId=3, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Hibernate: 
    select
        employee0_.employeeId as employee1_0_,
        employee0_.designation as designat2_0_,
        employee0_.firstName as firstNam3_0_,
        employee0_.joiningDate as joiningD4_0_,
        employee0_.lastName as lastName5_0_,
        employee0_.leavingDate as leavingD6_0_ 
    from
        EMPLOYEE employee0_ 
    where
        employee0_.designation=?

Employee [firstName=ABC98, lastName=XYZ18, employeeId=1, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Employee [firstName=ABC73, lastName=XYZ75, employeeId=2, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Employee [firstName=ABC13, lastName=XYZ61, employeeId=3, joiningDate=null, leavingDate=null, designation=Full Stack Java developer]
Oct 24, 2016 10:49:10 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@133ddba: startup date [Mon Oct 24 22:49:04 IST 2016]; root of context hierarchy

This is end of this tutorial. In next couple of tutorials, we will address two important issues where all database properties were hard coded in Spring context XML file to create SessionFactory and DataSource. We will see how we can move those to properties file. Another issue was, to manage transaction, we have to open session, begin transaction and then based on successful operation or not, either commit or rollback transaction. There is lot of boilerplate code in it. We will see how can we get rid of that using Spring managed transaction.

No comments:

Post a Comment