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

Thursday, October 23, 2014

Hibernate LOAD VS GET methods


Hibernate LOAD VS GET Methods

Most of the time the developers mix use the session.get() and session.load() hibernate methods, while they develop the applications. If they know the difference between the both of the methods, its may help to them to use those method properly. Not only that but also,  most of the technical interviews the developers faced the question regarding the difference between session.get() and session.load() methods..

In this tutorial the main objective is that, developers need to understand the session.get() and session.load() methods before they going to use in future.

But before going to list down the properties, both session.get() and session.load() methods are going to use for retrieve the objects. But there are bit differences.

The below table list down the session.get() method properties.

Get
get() involves database hits if the object does not in Session Cache, and return fully initialized object.
get() method returns null if object is not found in cache as well as on database
get() method is not return the proxy, but its returns fully initialized object or null.
Use of get() is little less performance compare with load()
Execution :
1
2
Session session = SessionFactory.getCurrentSession();
Student student = (Student) session.get(Student.class, StudentID);

The below table list down the session.load() method properties.

Load
load() can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object.
load() method throws ObjectNotFoundException instead of null, if object is not found on cache as well as on database
load() method may return proxy, which is the object with ID but without initializing other properties
Use of load() is littel better performance compare with get()
Execution :
1
2
Session session = SessionFactory.getCurrentSession();
Student student = (Student) session.load(Student.class, StudentID);

Wednesday, October 22, 2014

Spring MVC + Hibernate CRUD Web Application


Spring (4) MVC + Hibernate (4) CRUD Web Application

Scope : Develop an web application with using Spring and Hibernate

Objective : Develop a student management application with CRUD functionality.

Requirements : 
  • Eclipe Java EE IDE
  • JDK 1.6
  • MySQL Server 5.5
Step 1 : Create a dynamic web project in eclipse and name it as "SpringSimpleStudentMVC". 

Step 2 : The data base properties defined as below. 

/SpringSimpleStudentMVC/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 3 : Create a "Student" domain class under the "com.prem.domain" package.

/SpringSimpleStudentMVC/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 4 : Create "StudentDAO" and "StudentDAOImpl" interface and class file under the "com.prem.dao" package.

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


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 void updateStudent(Student student);

 public void deleteStudent(int id);
}

The "StudentDAOImpl" class looks like as below.

/SpringSimpleStudentMVC/src/com/prem/dao/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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.prem.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.prem.domain.Student;

public class StudentDAOImpl implements StudentDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 @Transactional
 public void saveStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();
 }

 @Override
 public List<Student> getAllStudent() {
  Session session = sessionFactory.openSession();
  List<Student> studentList = session.createQuery("from Student").list();
  session.close();
  return studentList;
 }

 @Override
 public Student getStudentById(int id) {
  Session session = sessionFactory.openSession();
  return (Student) session.load(Student.class, new Integer(id));
 }

 @Override
 public void updateStudent(Student student) {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();
  session.saveOrUpdate(student);
  tx.commit();
  Serializable id = session.getIdentifier(student);
  session.close();

 }

 @Override
 @Transactional
 public void deleteStudent(int id) {
  Session session = sessionFactory.openSession();  
    Transaction tx = session.beginTransaction();  
    Student student = (Student) session.load(Student.class, id);  
    session.delete(student);  
    tx.commit();  
    Serializable ids = session.getIdentifier(student);  
    session.close();  
 }

}

Step 5: Now the time to create a "StudentService" interface and the "StudentServiceManger" class under the "com.prem.service" package.

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


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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 void updateStudentDeatils(Student student);

 public void deleteStudentDetails(int id);
}

And the StudentServiceManger class as below.

/SpringSimpleStudentMVC/src/com/prem/service/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
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.prem.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.prem.dao.StudentDAO;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Service
public class StudentServiceManager implements StudentService {
 
 @Autowired
 private StudentDAO studentDAO;

 public StudentDAO getStudentDAO() {
  return studentDAO;
 }

 public void setStudentDAO(StudentDAO studentDAO) {
  this.studentDAO = studentDAO;
 }

 @Override
 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 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 void updateStudentDeatils(Student student) {
  studentDAO.updateStudent(student);
 }

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

}


Step 6 : Now we are going to create the "StudentController" class under the package "com.prem.controller".


/SpringSimpleStudentMVC/src/com/prem/controller/StudentController.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
67
package com.prem.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.prem.domain.Student;
import com.prem.service.StudentService;

@Controller
public class StudentController {

 @Autowired
 @Qualifier(value="studentService")
 StudentService studentService;

 public StudentService getStudentService() {
  return studentService;
 }

 public void setStudentService(StudentService studentService) {
  this.studentService = studentService;
 }

 @RequestMapping("form")
 public ModelAndView getForm(@ModelAttribute Student student) {
  return new ModelAndView("form");
 }

 @RequestMapping("register")
 @Transactional(readOnly=false)
 public ModelAndView registerUser(@ModelAttribute Student student) {
  studentService.saveStudentDetails(student);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("list")
 public ModelAndView getList() {
  List<Student> studentList = studentService.getAllStudents();
  return new ModelAndView("list", "studentList", studentList);
 }

 @RequestMapping("delete")
 public ModelAndView deleteUser(@RequestParam int id) {
  studentService.deleteStudentDetails(id);
  return new ModelAndView("redirect:list");
 }

 @RequestMapping("edit")
 public ModelAndView editUser(@RequestParam int id,
   @ModelAttribute Student student) {
  Student studentObject = studentService.getStudentDeatilsById(id);
  return new ModelAndView("edit", "studentObject", studentObject);
 }

 @RequestMapping("update")
 public ModelAndView updateUser(@ModelAttribute Student student) {
  studentService.updateStudentDeatils(student);
  return new ModelAndView("redirect:list");
 }

}


Step 7 : The spring configurations looks as below.

/SpringSimpleStudentMVC/WebContent/WEB-INF/mvc-dispatcher.xml


 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
<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:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
  
 <context:annotation-config />
 <context:property-placeholder location="classpath:database.properties" />
 <context:component-scan base-package="com.prem.dao.impl" />
 <context:component-scan base-package="com.prem.service.manager" />
 <context:component-scan base-package="com.prem.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="persistenceExceptionTranslationPostProcessor"
  class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

 <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.hibernate4.LocalSessionFactoryBean"
  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>
 
 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 
 <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
  id="hibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>

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


Step 8 : Now the time to create the jsp files for student registration.

/SpringSimpleStudentMVC/WebContent/WEB-INF/pages/form.jsp

 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
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Student Registration Form</title>  
</head>  
<body >  
 <center>  
  
  <div style="color: blue; font-size: 25px">Student  Registration Form</div>  
 
  <c:url var="userRegistration" value="saveUser.html" />  
  <form:form id="registerForm" modelAttribute="student" method="post" action="register">  
   <table width="500px" height="170px">  
    <tr>  
     <td><form:label path="firstName">First Name</form:label>  
     </td>  
     <td><form:input path="firstName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="lastName">Last Name</form:label>  
     </td>  
     <td><form:input path="lastName" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="email">Email</form:label>  
     </td>  
     <td><form:input path="email" />  
     </td>  
    </tr>  
    <tr>  
     <td><form:label path="phone">Phone</form:label>  
     </td>  
     <td><form:input path="phone" />  
     </td>  
    </tr>  
    <tr>  
     <td></td>  
     <td><input type="submit" value="Register" /></td>  
    </tr>  
   </table>  
  </form:form>  
  
  <a href="list">View All Students List</a>  
 </center>  
</body>  
</html>  

Step 9 : Now the time to run and see the behavior of the application.

The student registration screen looks like as below.





And the student details screen looks like as below.




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.