Code ví dụ Spring Boot với Hibernate Session + MySQL + Eclipse

Code ví dụ Spring Boot với Hibernate Session + MySQL + Eclipse

(Xem lại: Code ví dụ Spring MVC + Hibernate + Maven + MySQL + Eclipse)

Ở bài này mình sẽ sử dụng Hibernate Session để thực hiện ví dụ thêm, sửa, xóa dữ liệu với database MySQL.

(Xem lại Ví dụ Spring Boot JPA EntityManagerSự khác nhau Hibernate Session với JPA EntityManager)

Hiển thị dữ liệu lên màn hình với Thymleaf

Các công nghệ sử dụng:

Tạo Database

Tạo database spring-boot-hibernate với table customer

CREATE SCHEMA `spring-boot-hibernate` ;
CREATE TABLE `spring-boot-hibernate`.`customer` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `address` VARCHAR(255) NULL,
  PRIMARY KEY (`id`));

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + EclipseCode ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Tạo Spring Boot Project

Code ví dụ Spring Boot với Hibernate Session + MySQL + Eclipse stackjava.com

Ở bài này mình sẽ tạo project với Eclipse + Maven + Spring Tool Suite.

B1. Chọn File/New/Project –> Chọn Spring Starter Project

(Mục này chỉ hiện nếu bạn đã cài Spring Tool Suite)

https://stackjava.com/install/cai-dat-spring-tool-suite-cho-eclipse.html

B2. Chọn type, Java version và name cho Project

https://stackjava.com/install/cai-dat-spring-tool-suite-cho-eclipse.html

B3. Chọn các dependency cho Project

Sau khi chọn nó sẽ tự động thêm các dependency cần thiết vào file pom.xml

https://stackjava.com/install/cai-dat-spring-tool-suite-cho-eclipse.html

Cấu trúc Project:

project Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

 

Cấu hình Hibernate

Cấu hình các thông số connect tới database và config hibernate trong file application.properties.
# =============Database config==================
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-hibernate
spring.datasource.username=root
spring.datasource.password=admin1234

# ==============JPA / HIBERNATE=================
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Mặc định Spring Boot sẽ tự động cấu hình JPA và các bean liên quan gồm DataSourceAutoConfigurationDataSourceTransactionManagerAutoConfigurationHibernateJpaAutoConfiguration
Ở đây mình sử dụng Hibernate nên sẽ disable nó đi.
package stackjava.com.springboothibernate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({ "stackjava.com.springboothibernate" })
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
    DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
public class SpringBootHibernateApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHibernateApplication.class, args);
  }
}

 Tạo các bean cấu hình cho Hibernate

(Trong Spring, Spring MVC chúng ta sẽ config luôn trong file xml)

package stackjava.com.springboothibernate;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

@Configuration
public class BeanConfig {
  
  @Autowired
  private Environment env;
  
  @Bean(name = "dataSource")
  public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
  }

  @Autowired
  @Bean(name = "sessionFactory")
  public SessionFactory getSessionFactory(DataSource dataSource) throws Exception {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
    properties.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
    properties.put("current_session_context_class", //
        env.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));

    LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
    // Package contain entity classes
    factoryBean.setPackagesToScan("stackjava.com.springboothibernate.entities");
    factoryBean.setDataSource(dataSource);
    factoryBean.setHibernateProperties(properties);
    factoryBean.afterPropertiesSet();
    //
    SessionFactory sf = factoryBean.getObject();
    System.out.println("## getSessionFactory: " + sf);
    return sf;
  }

  @Autowired
  @Bean(name = "transactionManager")
  public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

    return transactionManager;
  }
}

File entity, dao, service, controller.

package stackjava.com.springboothibernate.entities;

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

@Entity
@Table(name = "customer")
public class Customer {
  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;

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

  @Column(name = "address")
  private String address;

  // getter - setter

}
package stackjava.com.springboothibernate.dao;

import java.util.List;

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

import stackjava.com.springboothibernate.entities.Customer;


@Repository(value = "customerDAO")
@Transactional(rollbackFor = Exception.class)
public class CustomerDAO {

  @Autowired
  private SessionFactory sessionFactory;

  public void save(final Customer customer) {
    Session session = this.sessionFactory.getCurrentSession();
    session.save(customer);
  }

  public void update(final Customer customer) {
    Session session = this.sessionFactory.getCurrentSession();
    session.update(customer);
  }

  public Customer findById(final int id) {
    Session session = this.sessionFactory.getCurrentSession();
    return session.get(Customer.class, id);
  }

  public void delete(final Customer customer) {
    Session session = this.sessionFactory.getCurrentSession();
    session.remove(customer);
  }

  public List<Customer> findAll() {
    Session session = this.sessionFactory.getCurrentSession();
    return session.createQuery("FROM Customer", Customer.class).getResultList();
  }
}
package stackjava.com.springboothibernate.service;

import java.util.List;

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

import stackjava.com.springboothibernate.dao.CustomerDAO;
import stackjava.com.springboothibernate.entities.Customer;

@Service
@Transactional
public class CustomerService {

  @Autowired
  private CustomerDAO customerDAO;

  public List<Customer> findAll() {
    return customerDAO.findAll();
  }

  public Customer findById(final int id) {
    return customerDAO.findById(id);
  }

  public void save(final Customer customer) {
    customerDAO.save(customer);
  }

  public void update(final Customer customer) {
    customerDAO.update(customer);
  }

  public void delete(final int id) {
    Customer customer = customerDAO.findById(id);
    if (customer != null) {
      customerDAO.delete(customer);
    }
  }
}
package stackjava.com.springboothibernate.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import stackjava.com.springboothibernate.entities.Customer;
import stackjava.com.springboothibernate.service.CustomerService;

@Controller
public class CustomerController {

  @Autowired
  private CustomerService customerService;

  @RequestMapping(value={"/", "/customer-list"})
  public String listCustomer(Model model) {
    model.addAttribute("listCustomer", customerService.findAll());
    return "customer-list";
  }

  @RequestMapping("/customer-save")
  public String insertCustomer(Model model) {
    model.addAttribute("customer", new Customer());
    return "customer-save";
  }

  @RequestMapping("/customer-view/{id}")
  public String viewCustomer(@PathVariable int id, Model model) {
    Customer customer = customerService.findById(id);
    model.addAttribute("customer", customer);
    return "customer-view";
  }
  
  @RequestMapping("/customer-update/{id}")
  public String updateCustomer(@PathVariable int id, Model model) {
    Customer customer = customerService.findById(id);
    model.addAttribute("customer", customer);
    return "customer-update";
  }

  @RequestMapping("/saveCustomer")
  public String doSaveCustomer(@ModelAttribute("Customer") Customer customer, Model model) {
    customerService.save(customer);
    model.addAttribute("listCustomer", customerService.findAll());
    return "redirect:customer-list";
  }

  @RequestMapping("/updateCustomer")
  public String doUpdateCustomer(@ModelAttribute("Customer") Customer customer, Model model) {
    customerService.update(customer);
    model.addAttribute("listCustomer", customerService.findAll());
    return "redirect:customer-list";
  }
  
  @RequestMapping("/customerDelete/{id}")
  public String doDeleteCustomer(@PathVariable int id, Model model) {
    customerService.delete(id);
    model.addAttribute("listCustomer", customerService.findAll());
    return "redirect:/customer-list";
  }
}

File view:

<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot - Hibernate</title>
<style>
table, th, td, tr {
  border: 1px solid black;
}

td {
  padding-right: 30px;
}
</style>
</head>
<body>
  <h1>List Customer:</h1>
  <a th:href="@{/customer-save}">Add Customer</a>
  <br />
  <br />

  <table>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Address</th>
      <th>View</th>
      <th>Edit</th>
      <th>Delete</th>
    </tr>
    <th:block th:each="customer : ${listCustomer}">
      <tr>
        <td><p th:text="${customer.id}"></p></td>
        <td><p th:text="${customer.name}"></p></td>
        <td><p th:text="${customer.address}"></p></td>
        <td><a th:href="@{/customer-view/} + ${customer.id}">View</a></td>
        <td><a th:href="@{/customer-update/} + ${customer.id}">Edit</a></td>
        <td><a th:href="@{/customerDelete/} + ${customer.id}">Delete</a></td>
      </tr>
    </th:block>
  </table>

</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot - Hibernate</title>
</head>
<body>
  <a th:href="@{/customer-list}">List Customer</a><br />

  <h1>Add new Customer:</h1>
  <form th:action="@{/saveCustomer}" method="POST" th:object="${customer}">
    	Name: <input th:field="*{name}"/> <br/> <br/>
    	Address: <input th:field="*{address}"/> <br/> <br/>
    <input type="submit" value="Submit" />
  </form>
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot - Hibernate</title>
</head>
<body>
  <a th:href="@{/customer-list}">List Customer</a> 
  <br/> <br/>
  
  <table>
    <tr>
      <td>Id: </td>
      <td><p th:text="${customer.id}"/></td>
    </tr>
    <tr>
      <td>Name: </td>
      <td><p th:text="${customer.name}"/></td>
    </tr>
    <tr>
      <td>Address: </td>
      <td><p th:text="${customer.address}"/></td>
    </tr>
  </table>
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot - Hibernate</title>
</head>
<body>
  <a th:href="@{/customer-list}">List Customer</a><br />

  <h1>Edit Customer:</h1>
  <form th:action="@{/updateCustomer}" method="POST" th:object="${customer}">
    	Id: <input th:field="*{id}" readonly="true" /> <br/> <br/>
    	Name: <input th:field="*{name}"/> <br/> <br/>
    	Address: <input th:field="*{address}"/> <br/> <br/>
    <input type="submit" value="Submit" />
  </form>
</body>
</html>

Demo:

  • Tạo mới customer:

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

  • Xem customer

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

  • Sửa customer

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

  • Xóa customer

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse

Code ví dụ Spring Boot với Hibernate Session + MySQL + Eclipse stackjava.com

Okay done!

Download code ví dụ trên tại đây

 

References:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-data-access

stackjava.com