Code ví dụ Spring Boot Data JPA (Hibernate EntityManager) + MySQL
Ở bài này mình sẽ sử dụng JPA EntityManager để 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 Hibernate Session, Sự 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:
- Spring Boot 2.0.2
- Maven
- JDK 1.8
- Eclipse + Spring Tool Suite
- Thymeleaf
Tạo Database
Tạo database spring-boot-jpa
với table customer
CREATE SCHEMA `spring-boot-jpa` ; CREATE TABLE `spring-boot-jpa`.`customer` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NULL, `address` VARCHAR(255) NULL, PRIMARY KEY (`id`));
Tạo Spring Boot Project
Cấu trúc project.
Cấu hình Hibernate – Database
application.properties
.# =============Database config================== spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-jpa spring.datasource.username=root spring.datasource.password=admin1234 # ==============JPA / HIBERNATE================= spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
File entity.
package stackjava.com.sbjpa.entities; import javax.persistence.*; @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 }
File DAO.
Mặc định khi bạn chọn thư viện JPA lúc tạo Project, Spring Boot sẽ tự động cấu hình JPA và các bean liên quan gồm DataSourceAutoConfiguration
, DataSourceTransactionManagerAutoConfiguration
, HibernateJpaAutoConfiguration
Do đó bạn chỉ cần sử dụng annotation @PersistenceContext
hoặc @Autowired
để sử dụng EntityManager
package stackjava.com.sbjpa.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import stackjava.com.sbjpa.entities.Customer; @Repository(value = "customerDAO") @Transactional(rollbackFor = Exception.class) public class CustomerDAO { @PersistenceContext private EntityManager entityManager; public void persist(final Customer customer) { entityManager.persist(customer); } public Customer findById(final int id) { return entityManager.find(Customer.class, id); } public void delete(final Customer customer) { entityManager.remove(customer); } public List<Customer> findAll() { return entityManager.createQuery("FROM Customer").getResultList(); } }
File Service.
package stackjava.com.sbjpa.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.sbjpa.dao.CustomerDAO; import stackjava.com.sbjpa.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) { // check if exist -> throw exception customerDAO.persist(customer); } public void update(final Customer customer) { // check if not exist -> throw excpetion Customer customerDb = customerDAO.findById(customer.getId()); customerDb.setName(customer.getName()); customerDb.setAddress(customer.getAddress()); customerDAO.persist(customerDb); } public void delete(final int id) { Customer customer = customerDAO.findById(id); if (customer != null) { customerDAO.delete(customer); } } }
File Controller.
package stackjava.com.sbjpa.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.sbjpa.entities.Customer; import stackjava.com.sbjpa.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"; } }
Các file views:
<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:
- Xem customer
- Sửa customer
- Xóa customer
Code ví dụ Spring Boot Data JPA (Hibernate EntityManager) + MySQL 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