Hôm nay mình sẽ gửi đến các bạn các bước để tạo 1 dự án sử dụng SpringBoot và Spring Data JPA.
Trước khi Spring Data JPA ra đời để tạo 1 project sử dụng Spring và JPA các bạn phải tạo các entity và tương ứng phải viêt các lớp Dao cho từng Entity này, công việc này lặp đi lặp lại tương ứng với mỗi entity.
Để giảm thiểu việc lặp lại này Spring đã bổ sung Spring Data JPA.
Ở ví dụ này mình dùng IDE: IntelliJ IDEA 2019.2.3 (Ultimate Edition), mình khuyên bạn nên dùng IDE này, các bạn có thể dùng các IDE khác hoặc vào vào https://start.spring.io/ để tạo nhé.
Đầu tiên là ở bước tạo project: Các bạn chọn tạo new Project và chọn Spring Initialzr
Bước tiếp theo chọn
Ở phần chọn Dependencies ở phần SQL bạn chọn Spring Data JPA và MySQL Driver(mình thực hiện ví dụ này bằng mysql để cho dễ nhé, bạn nào không có mysql thì có thể download xamp) còn ở phần Web bạn chọn Spring Web.
Xong các bạn chọn next và finish.
Kết quả như sau, bạn lưu ý là ở ví dụ này mình đang chọn tool build là Maven nhé, bạn có thể chọn gradle cũng được.
Bước tiếp theo chúng ta sẽ tạo database, đầu tiên bổ sung các thông tin vào file application.properties
# =============================== # DATABASE # =============================== spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/demodata?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password= # =============================== # JPA / HIBERNATE # =============================== spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Mìn sẽ tạo 1 database tên là demodata trong sql, mình dùng phpmyadmin để thao tác.
Tiếp theo là thêm entity
package gatostudy.com.springdatajpa.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id; private String firstName; private String lastName; protected Student() {} public Student(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format( "Student[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } public Long getId() { return id; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }
Spring Data JPA tập trung sử dụng JPA để thao tác liệu trong database. Nó linh động tạo ra repository để thi hành(implementation) tự động tại thời điểm chạy từ một giao diện(interface) repository.
Tạo interface StudentRepository
package gatostudy.com.springdatajpa.repository; import java.util.List; import gatostudy.com.springdatajpa.entity.Student; import org.springframework.data.repository.CrudRepository; public interface StudentRepository extends CrudRepository<Student, Long> { List<Student> findByLastName(String lastName); Student findById(long id); }
StudentRepository mở rộng(extend) từ giao diện(interface) CrudRepository. Bằng việc mở rộng(Extend) từ CrudRepository, StudentRepository thừa kế những phương thức để thao tác với đối tượng Student(còn gọi là persistence Student), bao gồm các phương thức cho việc lưu dữ liệu, xóa và tìm kiếm.
Spring Data JPA cho phép bạn định nghĩa các phương thức truy vấn bằng việc khai báo, ví dụ như hàm findByLastName trong ví dụ này.
Trong các ứng dụng Java khác, bạn sẽ nghĩ là cần khai báo một class để thi hành(implement) StudentRepository. Tuy nhiên với Spring Data JPA lại khác, đây là ưu điểu của nó, bạn không cần làm điều này, Spring Data JPA sẽ tạo một thi hành(Implement) khi bạn thực thi.
Để chạy ví dụ này bạn cần bổ sung code tạo bean CommandLineRunner, dưới đây là code của SpringdatajpaApplication sau khi bổ sung.
package gatostudy.com.springdatajpa; import gatostudy.com.springdatajpa.entity.Student; import gatostudy.com.springdatajpa.repository.StudentRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringdatajpaApplication { private static final Logger log = LoggerFactory.getLogger(SpringdatajpaApplication.class); public static void main(String[] args) { SpringApplication.run(SpringdatajpaApplication.class, args); } @Bean public CommandLineRunner demo(StudentRepository repository) { return (args) -> { // lưu vào một vài sinh viên repository.save(new Student("Lee", "Loan")); repository.save(new Student("Seo", "Ben")); repository.save(new Student("Pack", "HSeo")); repository.save(new Student("Michel", "Jon")); // Hiển thị tât cả sinh viên System.out.println("Students found with findAll():"); System.out.println("-------------------------------"); for (Student Student : repository.findAll()) { System.out.println(Student.toString()); } System.out.println(""); // Hiển thị sinh viên theo ID Student Student = repository.findById(1L); System.out.println("Tìm sinh viên theo findById(1L):"); System.out.println("--------------------------------"); System.out.println(Student.toString()); System.out.println(""); // Hiển thị theo last name System.out.println("Tìm kiến theo findByLastName('Loan'):"); System.out.println("--------------------------------------------"); repository.findByLastName("Loan").forEach(name -> { System.out.println(name.toString()); }); // for (Student name : repository.findByLastName("Loan")) { // System.out.println(name.toString()); // } System.out.println(""); }; } }
Đoạn code này mục đích tạo ra dữ liệu test và thực hiện 1 số hàm tìm kiếm.
Đây là kết quả chạy sẽ tương tự như này.
Đến đây các bạn cũng có thể tạo thêm các class Controller để test như là API rest.
Tôi sẽ tạo thử 1 lớp StudentController
package gatostudy.com.springdatajpa.controller; import gatostudy.com.springdatajpa.entity.Student; import gatostudy.com.springdatajpa.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/students") public class StudentController { @Autowired StudentRepository studentRepo; @GetMapping public List<Student> getStudents() { return (List<Student>) studentRepo.findAll(); } @PostMapping public void postStudent(@RequestBody Student dto) { studentRepo.save(dto); } @GetMapping("/{id}") public Student getById(@PathVariable(required = true) long id) { return studentRepo.findById(id); } @DeleteMapping("/{id}") public void delete(@PathVariable(required = true) long id) { studentRepo.deleteById(id); } }
Bạn thực hiện chạy chương trình và mở trình duyệt gõ
http://localhost:8080/students
Kết quả sẽ là, có kết quả này vì lúc trước chúng ta đã insert dữ liệu vào bảng student rồi.
Cảm ơn các bạn đã theo dõi.