I. Giới thiệu về sự kết hợp giữa Spring và Hibernate

Hibernate và Spring là mã nguồn mở Java khuôn khổ mà đơn giản hóa việc phát triển các ứng dụng Java / JEE, ứng dụng độc lập chạy trên một JVM duy nhất, từ đơn giản cho đến các ứng dụng phức tạp, chạy trên các máy chủ ứng dụng toàn diện. Hibernate và Spring cho phép các nhà phát triển để tạo ra khả năng mở rộng, đáng tin cậy, và hiệu quả.

Mặc dù mục đích của các khuôn khổ một phần chồng lên nhau, đối với hầu hết các phần, từng được sử dụng cho một mục đích khác nhau. Hibernate framework nhằm giải quyết các vấn đề quản lý dữ liệu trong Java:API Java, JDBC (Java Database Connectivity), persistence providers , DBMS (Database Management Systems), và là ngôn ngữ trung gian, SQL (Structured Query Language).

Ngược lại, Spring là một khung nhiều tầng mà không dành riêng cho một khu vực kiến trúc ứng dụng cụ thể . Tuy nhiên, Spring không cung cấp giải pháp riêng của mình cho các vấn đề như sự kiên trì, mà đã có giải pháp tốt. Thay vào đó, Spring thống nhất các giải pháp từ trước dưới API nhất quán của nó và làm cho họ dễ dàng hơn để sử dụng. Như đã đề cập, một trong những khu vực này là persistence. Spring có thể được tích hợp với một persistence solution, như Hibernate, để cung cấp một lớp trừu tượng, quản lý, và có hiệu quả.

II. Kết nối database

  1. Tạo DB với MySQL

Tạo 1 database tên studentdb với bảng là student có cấu trúc bảng như sau:

  1. Tạo Spring project

2.1 Tạo 1 dynamic web project tên KetNoiDB, add new folder cho project:

 Convert sang maven project và add maven vào thư viện của project

Cấu hình file pom để sử dụng spring, hibernate và MySQl như dưới đây:


 
  4.0.0
 
  CRUDWebAppMavenized
 
  CRUDWebAppMavenized
 
  0.0.1-SNAPSHOT
 
  war
 
  
 
3.0.5.RELEASE
 
  
 
  
 

 
org.springframework
 
spring-core
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-beans
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-context
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-web
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-webmvc
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-jdbc
 
${org.springframework.version}
 

 

 
org.springframework
 
spring-orm
 
${org.springframework.version}
 

 

 

 
org.hibernate
 
hibernate-entitymanager
 
3.6.7.Final
 

 

 
org.hibernate
 
hibernate-validator
 
4.3.0.Final
 

 

 
org.hibernate
 
hibernate-commons-annotations
 
3.3.0.ga
 

 

 
org.hibernate
 
hibernate-annotations
 
3.3.1.GA
 

 

 
org.hibernate
 
hibernate-core
 
3.3.2.GA
 

 

 
taglibs
 
standard
 
1.1.2
 

 

 
javax.servlet
 
jstl
 
1.1.2
 

 

 
commons-dbcp
 
commons-dbcp
 
20030825.184428
 

 

 
commons-pool
 
commons-pool
 
20030825.183949
 

 

 

 
mysql
 
mysql-connector-java
 
5.1.6
 

 

 

 
log4j
 
log4j
 
1.2.14
 
jar
 
compile
 

 

 
  
 
    src/main/test
 
    
 
  
 
    src/main/resources
 
    
 
      **/*.java
 
    
 
  
 
  
 
    src/main/webapp
 
    
 
      **/*.java
 
    
 
  
 

 

 
  
 
    maven-compiler-plugin
 
    2.4
 
    
 
      1.7
 
      1.7
 
    
 
  
 
    
 
  
 

 

2.2 Tạo file jdbc.properties để cấu hình sử dụng DB

Vào src\main\webapp tạo new file và đặt tên là jdbc.properties:

 
jdbc.driverClassName=com.mysql.jdbc.Driver
 
jdbc.dialect=org.hibernate.dialect.MySQLDialect
 
jdbc.databaseurl=jdbc:mysql://localhost:3306/studentdb
 
jdbc.username=root
 
jdbc.password=123456
 

Day là config de connect voi DB MySQl

Tạo các file, folder theo hình sau:

2.3 Nội dung của cá file như sau:

2.3.1 com.nhungnth.model/student.java

package com.nhungnth.model;
 
 /*
* Khai bao cac bien lay tu bang Student
* */
 
import javax.persistence.Column;
 
import javax.persistence.Entity;
 
import javax.persistence.GeneratedValue;
 
import javax.persistence.GenerationType;
 
import javax.persistence.Id;
 
@Entity
 
public class Student {
 
@Id
 
@Column
 
@GeneratedValue(strategy=GenerationType.AUTO) //for autonumber
 
private int studentId;
 
@Column
 
private String firstname;
 
@Column
 
private String lastname;
 
@Column
 
private int yearLevel;
 
public Student(){}
 
public Student(int studentId, String firstname, String lastname,
 
int yearLevel) {
 
super();
 
this.studentId = studentId;
 
this.firstname = firstname;
 
this.lastname = lastname;
 
this.yearLevel = yearLevel;
 
}
 
public int getStudentId() {
 
return studentId;
 
}
 
public void setStudentId(int studentId) {
 
this.studentId = studentId;
 
}
 
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 int getYearLevel() {
 
return yearLevel;
 
}
 
public void setYearLevel(int yearLevel) {
 
this.yearLevel = yearLevel;
 
}
 
}
 

2.3.2 com.nhungnth.dao/StudentDao.java

package com.nhungnth.dao;
 
 /*
* Khai bao cac ham add, edit, delete... can su dung
* */
 
import java.util.List;
 
import com.nhungnth.model.Student;
 
public interface StudentDao {
 
public void add(Student student);
 
public void edit(Student student);
 
public void delete(int studentId);
 
public Student getStudent(int studentId);
 
public List getAllStudent();
 
}
 

2.3.3 com.nhungnth.dao.impl/StudentDaoImpl.java

package com.nhungnth.dao.impl;
 
 /*
*  Dao implement interface
* */
 
import java.util.List;
 
import org.hibernate.SessionFactory;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Repository;
 
import com.nhungnth.dao.StudentDao;
 
import com.nhungnth.model.Student;
 
@Repository
 
public class StudentDaoImpl implements StudentDao {
 
@Autowired
 
private SessionFactory session;
 
@Override
 
public void add(Student student) {
 
session.getCurrentSession().save(student);
 
}
 
@Override
 
public void edit(Student student) {
 
session.getCurrentSession().update(student);
 
}
 
@Override
 
public void delete(int studentId) {
 
session.getCurrentSession().delete(getStudent(studentId));
 
}
 
@Override
 
public Student getStudent(int studentId)     {
 
return (Student)session.getCurrentSession().get(Student.class, studentId);
 
}
 
@Override
 
public List getAllStudent() {
 
return session.getCurrentSession().createQuery("from Student").list();
 
}
 
}

2.3.4 com.nhungnth.service/StudentService.java

package com.nhungnth.service;
 
 /*
*  model interface
* */
 
import java.util.List;
 
import com.nhungnth.model.Student;
 
public interface StudentService {
 
public void add(Student student);
 
public void edit(Student student);
 
public void delete(int studentId);
 
public Student getStudent(int studentId);
 
public List getAllStudent();
 

2.3.5 com.nhungnth.service.impl/StudentServiceImpl.java

package com.nhungnth.service.impl;
 
 /*
*  service implement
* */
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Service;
 
import org.springframework.transaction.annotation.Transactional;
 
import com.nhungnth.dao.StudentDao;
 
import com.nhungnth.model.Student;
 
import com.nhungnth.service.StudentService;
 
@Service
 
public class StudentServiceImpl implements StudentService {
 
@Autowired
 
private StudentDao studentDao;
 
@Transactional
 
public void add(Student student) {
 
studentDao.add(student);
 
}
 
@Transactional
 
public void edit(Student student) {
 
studentDao.edit(student);
 
}
 
@Transactional
 
public void delete(int studentId) {
 
studentDao.delete(studentId);
 
}
 
@Transactional
 
public Student getStudent(int studentId)     {
 
return studentDao.getStudent(studentId);
 
}
 
@Transactional
 
public List getAllStudent() {
 
return studentDao.getAllStudent();
 
}
 
}

2.3.6 com.nhungnth.controller/StudentController.java

package com.nhungnth.controller;
 
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.stereotype.Controller;
 
import org.springframework.validation.BindingResult;
 
import org.springframework.web.bind.annotation.ModelAttribute;
 
import org.springframework.web.bind.annotation.RequestMapping;
 
import org.springframework.web.bind.annotation.RequestMethod;
 
import org.springframework.web.bind.annotation.RequestParam;
 
import com.nhungnth.model.Student;
 
import com.nhungnth.service.StudentService;
 
 /*
*  action comtroller
 
*  thuc hien thao tac qua lai giua db va     view
* */
 
@Controller
 
public class StudentController {
 
@Autowired
 
private StudentService studentService;
 
@RequestMapping("/index")
 
public String setupForm(Map map){
 
Student student = new Student();
 
map.put("student", student);
 
map.put("studentList", studentService.getAllStudent());
 
return "student";
 
}
 
@RequestMapping(value="/student.do", method=RequestMethod.POST)
 
public String doActions(@ModelAttribute Student student, BindingResult result, @RequestParam String action, Map map){
 
Student studentResult = new Student();
 
switch(action.toLowerCase()){//only in Java7 you can put String in switch
 
case "add":
 
studentService.add(student);
 
studentResult = student;
 
break;
 
case "edit":
 
studentService.edit(student);
 
studentResult = student;
 
break;
 
case "delete":
 
studentService.delete(student.getStudentId());
 
studentResult = new Student();
 
break;
 
case "search":
 
Student searchedStudent = studentService.getStudent(student.getStudentId());
 
studentResult = searchedStudent!=null ? searchedStudent : new Student();
 
break;
 
}
 
map.put("student", studentResult);
 
map.put("studentList",                      studentService.getAllStudent());
 
return "student";
 
}
 
}

2.4 tạo các file view cho webapp

2.4.1 src/main/webapp/jsp/includes.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
 
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
 
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

2.4.2 src/main/webapp/jsp/student.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 
pageEncoding="ISO-8859-1"%>
 
<%@ include file="/WEB-INF/jsp/includes.jsp"%>
 

 

Student Management

Students Data

 

Student ID 
First name 
Last name 
Year Level 
 

 

IDFirst nameLast nameYear level
${student.studentId}${student.firstname}${student.lastname}${student.yearLevel}

2.5 Cấu hình của các file log4j.xml, hibernate.cfg.xml và web.xml:

2.5.1 src\main\resources\log4j.xml — ghi lai log

 

 

 

 

 

 


 
               
 
 
 

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

2.5.2 src\main\resources\hibernate.cfg.xml — cofig cho file hibernate


 
  
 
 
 
             
 
    
 
              
 
 

2.5.3 src\main\webapp\spring-servlet.xml — cấu hình file servlet


 
 
 
 
 
 
 
 

p:location=”/WEB-INF/jdbc.properties” />



 
 
 
 
 
 
 
 classpath:hibernate.cfg.xml
 
 
 
 
 
 org.hibernate.cfg.AnnotationConfiguration
 
 
 
 
 
 
 
 ${jdbc.dialect}
 
 true
 
 
 
 
 
 
 
 
 
     
 

 
     
 
 
 
 
 
 
 
 
 
 
 
 

2.5.4 src\main\webapp\web.xml



 
 
 
   KETNOIDB
 
   
 
 log4jConfigLocation
 
 classpath:log4j.xml
 
 
 
 
 
 org.springframework.web.util.Log4jConfigListener
 
 
 
 
 
 spring
 
 org.springframework.web.servlet.DispatcherServlet
 
 1
 
 
 
 
 
 spring
 
 /
 
 
 
   
 
     index.html
 
     index.htm
 
     index.jsp
 
     default.html
 
     default.htm
 
     default.jsp
 
   
 
 

Kết luận: Refesh lại project và start server để run project

Lợi thế khi dùng Hibernate:

  • Nâng suất: không viết code sql, ít viết code java
  • Hiệu suất: cahce
  • Dễ bảo trì
  • linh hoạt: do generate code sql, có thể tùy chỉnh sql *Nhược điểm của Hibernate Chậm hơn jdbc do phải generate code sql

Nguồn: https://techtalk.vn/ket-noi-database-voi-java-spring.html