Friday, October 17, 2014

Spring Hibernate Dao Support CRUD Application


Spring (3) Hibernate (3) Dao Support CRUD Application

Scope : Develop an application with using Spring Hibernate DAO support.

Objective : Implement a Student management java application with CRUD functionality

Requirements:
  • Eclipse JAVA EE IDE
  • JDK 1.6
  • My SQL Server 5.5

Step 1: Create a Java project In eclipse and named as "SpringSimpleStudent”.
File > New > Java project 

Add the following jars to your build path.
  • asm.jar
  • asm-attrs.jar
  • cglib-2.1.3.jar
  • commons-collections-2.1.1.jar
  • commons-logging-1.1.jar
  • dom4j-1.6.1.jar
  • hibernate3.jar
  • hibernate-annotations.jar
  • hibernate-commons-annotations.jar
  • hibernate-entitymanager.jar
  • javaee.jar
  • javax.persistence.jar
  • jstl.jar
  • mysql-connector.jar
  • servlet-api.jar
  • spring related jars...
Find below the project structure for our example.


Step 2: First we create the "Student" Domain class for this example.

/SpringSimpleStudent/src/com/prem/domain/Student.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.prem.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {
 @Id
 @GeneratedValue
 private int id;

 @Column(name = "FIRSTNAME")
 private String firstName;

 @Column(name = "LASTNAME")
 private String lastName;

 @Column(name = "EMAIL")
 private String email;

 @Column(name = "CONTACTNO")
 private String phone;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

}

Step 3: Create a "StudentDAO" interface and "StudentDAOImpl" class for to do the data base persistence.
StudentDAO class as below.

/SpringSimpleStudent/src/com/prem/dao/StudentDAO.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.prem.dao;

import java.util.List;

import com.prem.domain.Student;

public interface StudentDAO {

 public void saveStudent(Student student);

 public List<Student> getAllStudent();

 public Student getStudentById(int id);

 public int updateStudent(Student student);

 public int deleteStudent(int id);
}


And the StudentDAOImpl class as below.


/SpringSimpleStudent/src/com/prem/dao/impl/StudentDAOImpl.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 com.prem.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.prem.dao.StudentDAO;
import com.prem.domain.Student;

public class StudentDAOImpl extends HibernateDaoSupport implements StudentDAO {

 @Autowired
 public void init(SessionFactory factory) {
  setSessionFactory(factory);
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  getHibernateTemplate().save(student);
 }

 @Override
 public List<Student> getAllStudent() {
  return (List<Student>) getHibernateTemplate().loadAll(Student.class);
 }

 @Override
 public Student getStudentById(int id) {
  return (Student) getHibernateTemplate().get(Student.class, id);
 }

 @Override
 public int updateStudent(Student student) {
  getHibernateTemplate().update(student);
  return 0;
 }

 @Override
 public int deleteStudent(int id) {
  getHibernateTemplate().delete(getStudentById(id));
  return 0;
 }

}


Step 4: Now the time to create the "StudentService" interface and the "StudentServiceManager" class for manage the business logic.

The "StudentService" interface looks as below.


/SpringSimpleStudent/src/com/prem/service/StudentService.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.prem.service;

import java.util.List;

import com.prem.domain.Student;

public interface StudentService {
 public void saveStudentDetails(Student student);

 public List<Student> getAllStudents();

 public Student getStudentDeatilsById(int id);

 public int updateStudentDeatils(Student student);

 public int deleteStudentDetails(int id);
}
And the "StudentServiceManager" class as below.

/SpringSimpleStudent/src/com/prem/service/manager/StudentServiceManager.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
package com.prem.service.manager;

import java.util.List;

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

import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

public class StudentServiceManager implements StudentService {
 @Autowired
 StudentDAO studentDAO;

 @Override
 public void saveStudentDetails(Student student) {
  studentDAO.saveStudent(student);
 }

 @Override
 public List<Student> getAllStudents() {
  return studentDAO.getAllStudent();
 }

 @Override
 public Student getStudentDeatilsById(int id) {
  return studentDAO.getStudentById(id);
 }

 @Override
 public int updateStudentDeatils(Student student) {
  return studentDAO.updateStudent(student);
 }

 @Override
 public int deleteStudentDetails(int id) {
  return studentDAO.deleteStudent(id);
 }

}

Step 5: In this example we are going to define the data base access parameters in a "database.properties" properties file.

The "database.properties" file contains the following parameters as key value pairs.


/SpringSimpleStudent/src/database.properties


1
2
3
4
5
6
7
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=1234
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect
Step 6: Now the time comes to play with the spring configurations.
In this example I am not going to create any hibernate configuration file. Instead of that I already defined the domain class with the annotation.

/SpringSimpleStudent/src/spring-config.xml

The "spring-config" file looks as below.

 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
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 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">
 <context:annotation-config />

 <bean
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="database.properties" />
 </bean>

 <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  id="dataSource">
  <property name="driverClassName" value="${database.driver}"></property>
  <property name="url" value="${database.url}"></property>
  <property name="username" value="${database.user}"></property>
  <property name="password" value="${database.password}"></property>
 </bean>

 <bean
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
  id="sessionFactory">
  <property name="dataSource" ref="dataSource"></property>
  <property name="annotatedClasses">
   <list>
    <value>com.prem.domain.Student</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
   </props>
  </property>
 </bean>

 <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

 <bean id="dataDaoImpl" class="com.prem.dao.impl.StudentDAOImpl" />
 <bean id="studentDAO" class="com.prem.service.manager.StudentServiceManager" />
</beans>


That's all...  
Now the time to implement the Test class for this application. 

For this example I developed "StudentsOperationTest" class and its looks as below.


/SpringSimpleStudent/src/com/prem/test/StudentsOperationTest.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.prem.test;

import java.util.List;

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

import com.prem.domain.Student;
import com.prem.service.StudentService;
import com.prem.service.manager.StudentServiceManager;

public class StudentsOperationTest {
 public static void main(String[] args) {
  
  ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
  StudentServiceManager studentManager = (StudentServiceManager)appContext.getBean("studentDAO");
  
  // Save 1st student details
  Student student = new Student();
  student.setEmail("test@tester.com");
  student.setFirstName("John");
  student.setLastName("Smith");
  student.setPhone("1234567890");
  studentManager.saveStudentDetails(student);
  
  System.out.println("------- First Student details added ---- " + student.getFirstName());
  
  // Save 2nd student details
  Student student2 = new Student();
  student2.setEmail("dinesh@gmail.com");
  student2.setFirstName("Dinesh");
  student2.setLastName("Karthik");
  student2.setPhone("1234543210");
  studentManager.saveStudentDetails(student2);
  System.out.println("------- Second Student details added ---- " + student2.getFirstName());
  
  // Get first student details
  Student firstStudent = studentManager.getStudentDeatilsById(1);
  
  // Get All students phone numbers
  List<Student> students = studentManager.getAllStudents();
  System.out.println("---------ALL STUDENTS PHONE NO ----------");
  for (Student stu : students) {
   System.out.println(stu.getFirstName() + "---" + stu.getPhone());
  }
  
  // Update firstStudent phone number
  firstStudent.setPhone("0001112222");
  studentManager.updateStudentDeatils(firstStudent);
  System.out.println("------- First Student details updated ---- " + firstStudent.getPhone());
  
  // Get All students phone numbers
  students = studentManager.getAllStudents();
  System.out.println("---------ALL STUDENTS PHONE NO ----------");
  for (Student stu : students) {
   System.out.println(stu.getFirstName() + "---" + stu.getPhone());
  }
  
  // Delete last student details
  studentManager.deleteStudentDetails(2);
  System.out.println("------- Second Student details deleted ---- ");
  
 }
}
Once you run the "StudentsOperationTest" class you able to see the following output from your java console.


 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
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: table not found: Student
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: table not found: Student
Oct 17, 2014 5:00:01 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: schema update complete
Oct 17, 2014 5:00:01 PM org.springframework.orm.hibernate3.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@29c58e] of Hibernate SessionFactory for HibernateTransactionManager
Hibernate: insert into Student (EMAIL, FIRSTNAME, LASTNAME, CONTACTNO) values (?, ?, ?, ?)
------- First Student details added ---- John
Hibernate: insert into Student (EMAIL, FIRSTNAME, LASTNAME, CONTACTNO) values (?, ?, ?, ?)
------- Second Student details added ---- Dinesh
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.FIRSTNAME as FIRSTNAME0_0_, student0_.LASTNAME as LASTNAME0_0_, student0_.CONTACTNO as CONTACTNO0_0_ from Student student0_ where student0_.id=?
Hibernate: select this_.id as id0_0_, this_.EMAIL as EMAIL0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.CONTACTNO as CONTACTNO0_0_ from Student this_
---------ALL STUDENTS PHONE NO ----------
John---1234567890
Dinesh---1234543210
Hibernate: update Student set EMAIL=?, FIRSTNAME=?, LASTNAME=?, CONTACTNO=? where id=?
------- First Student details updated ---- 0001112222
Hibernate: select this_.id as id0_0_, this_.EMAIL as EMAIL0_0_, this_.FIRSTNAME as FIRSTNAME0_0_, this_.LASTNAME as LASTNAME0_0_, this_.CONTACTNO as CONTACTNO0_0_ from Student this_
---------ALL STUDENTS PHONE NO ----------
John---0001112222
Dinesh---1234543210
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.FIRSTNAME as FIRSTNAME0_0_, student0_.LASTNAME as LASTNAME0_0_, student0_.CONTACTNO as CONTACTNO0_0_ from Student student0_ where student0_.id=?
Hibernate: delete from Student where id=?
------- Second Student details deleted ---- 

- In this example I did not create the Student table in MySQL manually. The table automatically generated through hibernate. You able to see those entries from the console out put lines 3-6.




No comments:

Post a Comment