• Home
  • Java
    • All
    • Các ide để lâp trình Java
    • Java-core

    Thuật toán sắp xếp Bubble sort(Sắp xếp nổi bọt)

    Sử dụng ThreadPool và Executor trong Java qua ví dụ

    Ghi Log trong java – Thực hiện như thế nào cho đúng ?

    Ghi Log trong java – Thực hiện như thế nào cho đúng ?

    Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

    Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

    Lộ trình để trở thành Java Dev

    Trending Tags

    • Spring framework
    • Hibernate-JPA
    • Database
      • All
      • Mysql
      • Oracle Database

      Select for update in Oracle

      HOW TO SETUP MYSQL 5.7 REPLICATION WITH MONITORING ON UBUNTU 16.04

      Trending Tags

    • Utility Library
      • All
      • Guava Cache
      Thực hành Cache Guava Cache trong ứng dụng Spring Boot

      Thực hành Cache Guava Cache trong ứng dụng Spring Boot

    • Tech News
    No Result
    View All Result
    • Home
    • Java
      • All
      • Các ide để lâp trình Java
      • Java-core

      Thuật toán sắp xếp Bubble sort(Sắp xếp nổi bọt)

      Sử dụng ThreadPool và Executor trong Java qua ví dụ

      Ghi Log trong java – Thực hiện như thế nào cho đúng ?

      Ghi Log trong java – Thực hiện như thế nào cho đúng ?

      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      Lộ trình để trở thành Java Dev

      Trending Tags

      • Spring framework
      • Hibernate-JPA
      • Database
        • All
        • Mysql
        • Oracle Database

        Select for update in Oracle

        HOW TO SETUP MYSQL 5.7 REPLICATION WITH MONITORING ON UBUNTU 16.04

        Trending Tags

      • Utility Library
        • All
        • Guava Cache
        Thực hành Cache Guava Cache trong ứng dụng Spring Boot

        Thực hành Cache Guava Cache trong ứng dụng Spring Boot

      • Tech News
      No Result
      View All Result
      Gà Tồ Study
      No Result
      View All Result
      Home Spring framework

      Hướng dẫn kết hợp Spring Data JPA với SpringBoot qua ví dụ

      gatostudy by gatostudy
      14 November, 2019
      in Hibernate-JPA
      0
      Hướng dẫn kết hợp Spring Data JPA với SpringBoot qua ví dụ
      0
      SHARES
      1.6k
      VIEWS
      Share on FacebookShare on Twitter

      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.

      Tags: spring data jpaspringboot
      Previous Post

      Thực hành Cache Guava Cache trong ứng dụng Spring Boot

      Next Post

      Thực hiện clustering và session replication cho tomcat

      Next Post
      Thực hiện clustering và session replication cho tomcat

      Thực hiện clustering và session replication cho tomcat

      Leave a Reply Cancel reply

      • Trending
      • Comments
      • Latest
      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      24 June, 2020
      Spring Data JPA – Giới thiệu các tính năng và cách sử dụng

      Spring Data JPA – Giới thiệu các tính năng và cách sử dụng

      13 November, 2019
      Ghi Log trong java – Thực hiện như thế nào cho đúng ?

      Ghi Log trong java – Thực hiện như thế nào cho đúng ?

      29 November, 2019
      Hướng dẫn kết hợp Spring Data JPA với SpringBoot qua ví dụ

      Hướng dẫn kết hợp Spring Data JPA với SpringBoot qua ví dụ

      14 November, 2019

      Sử dụng ThreadPool và Executor trong Java qua ví dụ

      1
      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

      1

      Select for update in Oracle

      0
      Designing a better architecture for a Node.js API

      Designing a better architecture for a Node.js API

      0

      Select for update in Oracle

      23 January, 2022

      HOW TO SETUP MYSQL 5.7 REPLICATION WITH MONITORING ON UBUNTU 16.04

      3 October, 2021

      20 May, 2021

      Giải thuật tìm kiếm nhị phân- Binary Search

      10 March, 2020

      Bài Viết Phổ Biến

      • Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

        Hướng dẫn cài đặt và sử dụng IntelliJ IDEA cơ bản

        0 shares
        Share 0 Tweet 0
      • Spring Data JPA – Giới thiệu các tính năng và cách sử dụng

        0 shares
        Share 0 Tweet 0
      • Ghi Log trong java – Thực hiện như thế nào cho đúng ?

        0 shares
        Share 0 Tweet 0
      • Hướng dẫn kết hợp Spring Data JPA với SpringBoot qua ví dụ

        0 shares
        Share 0 Tweet 0
      • Thực hành Cache Guava Cache trong ứng dụng Spring Boot

        0 shares
        Share 0 Tweet 0

      Theo dõi blog qua email

      Nhập địa chỉ email của bạn để đăng ký theo dõi và nhận thông báo về các bài mới qua email.

      Join 2 other subscribers

      Gà Tồ Study

      © 2019 Gato Study - Vì một Việt Nam tươi đẹp .

      Keep Camp & Keep Coding

      • About
      • Advertise
      • Careers
      • Contact

      Follow Us

      No Result
      View All Result
      • Home
      • Hibernate-JPA
      • Spring framework
      • Java
      • Api clients
      • Utility Library
      • Guava Cache
      • Apache commons
      • Oracle Database
      • Database
      • Mysql
      • Tech
      • MongoDB
      • Food

      © 2019 Gato Study - Vì một Việt Nam tươi đẹp .