Code ví dụ Spring Boot Data JPA (JpaRepository) MySQL + Eclipse
(Xem lại: Code ví dụ Spring Boot với Hibernate + MySQL + Maven + Eclipse)
Ở bài này mình sẽ sử dụng Spring Boot với Spring Data JPA để thực hiện ví dụ thêm, sửa, xóa dữ liệu với database MySQL. Sau đó hiển thị dữ liệu lên trình duyệt web 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-data với table customer
CREATE DATABASE IF NOT EXISTS `spring-data`; CREATE TABLE `spring-data`.`customer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) );
Tạo Spring Boot Project
Cấu trúc project.
Cấu hình Hibernate
application.properties
.## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/spring-data?useSSL=false 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
Mặc định Spring Boot sẽ tự động cấu hình JPA và các bean liên quan gồm DataSourceAutoConfiguration
, DataSourceTransactionManagerAutoConfiguration
, HibernateJpaAutoConfiguration
theo cấu hình trong file application.properties
File Repository
package stackjava.com.sbdatajpa.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import stackjava.com.sbdatajpa.entities.Customer; @Repository public interface CustomerRepository extends JpaRepository<Customer, Integer> { }
Khi extends JpaRepository ta có thể sử dụng luôn các method như findAll
, findById
, save
, delete
, deleteById
…mà không cần phải tạo các class DAO cho nó.
File entity
package stackjava.com.sbdatajpa.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 }
File Controller
package stackjava.com.sbdatajpa.controller; import java.util.Optional; 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.sbdatajpa.entities.Customer; import stackjava.com.sbdatajpa.repository.CustomerRepository; @Controller public class CustomerController { @Autowired private CustomerRepository customerRepository; @RequestMapping(value={"/", "/customer-list"}) public String listCustomer(Model model) { model.addAttribute("listCustomer", customerRepository.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) { Optional<Customer> customer = customerRepository.findById(id); if (customer.isPresent()) { model.addAttribute("customer", customer.get()); } return "customer-view"; } @RequestMapping("/customer-update/{id}") public String updateCustomer(@PathVariable int id, Model model) { Optional<Customer> customer = customerRepository.findById(id); if (customer.isPresent()) { model.addAttribute("customer", customer.get()); } return "customer-update"; } @RequestMapping("/saveCustomer") public String doSaveCustomer(@ModelAttribute("Customer") Customer customer, Model model) { customerRepository.save(customer); model.addAttribute("listCustomer", customerRepository.findAll()); return "customer-list"; } @RequestMapping("/updateCustomer") public String doUpdateCustomer(@ModelAttribute("Customer") Customer customer, Model model) { customerRepository.save(customer); model.addAttribute("listCustomer", customerRepository.findAll()); return "customer-list"; } @RequestMapping("/customerDelete/{id}") public String doDeleteCustomer(@PathVariable int id, Model model) { customerRepository.deleteById(id); model.addAttribute("listCustomer", customerRepository.findAll()); return "customer-list"; } }
Các 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:
- Xem customer
- Sửa customer
- Xóa customer
Rõ ràng với việc sử dụng Spring Data JPA việc cấu hình đơn giản đi rất nhiều.
Phần tiếp theo mình sẽ làm các ví dụ khác với Spring Data JPA như tạo các truy vấn phức tạp, phân trang…
Code ví dụ Spring Boot Data JPA (JpaRepository) MySQL + Eclipse stackjava.com
Okay, Done!
Download code ví dụ trên tại đây.
References:
https://docs.spring.io/spring-data/jpa/docs/2.1.0.M2/reference/html/
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle