post-image

Hướng dẫn sử dụng Spring Data JPA

Spring Data JPA

Trong bài viết này, chúng tôi sẽ chỉ cho bạn cách sử dụng Spring Boot + Spring Data JPA để lưu dữ liệu vào database H2 trong bộ nhớ và cách cũng truy vấn dữ liệu. Cùng bắt đầu luôn nhé 😉

Chúng ta có thể tạo project tại đây. Thêm các dependency như hình dưới rồi chọn GENERATE.

spring-initializr

1. Project Directory

project-directory

2. Maven

pom.xml:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com</groupId> <artifactId>hdd</artifactId> <version>0.0.1-SNAPSHOT</version> <name>hdd</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Code language: HTML, XML (xml)

Tổng hợp 200+ tài liệu, sách, bài thực hành, video hướng dẫn lập trình… từ cơ bản đến nâng cao

application.properties:

logging.level.org.springframework=INFO logging.level.com.hdd=INFO logging.level.com.zaxxer=DEBUG logging.level.root=ERROR spring.datasource.hikari.connectionTimeout=20000 spring.datasource.hikari.maximumPoolSize=5 spring.datasource.hikari.poolName=HikariPoolZZZ

3. Spring Data JPA

Product.java

package com.hdd; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Product() { } public Product(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Code language: JavaScript (javascript)

Tài liệu học lập trình: https://codegym.vn/tai-nguyen-hoc-lap-trinh/

ProductRepository.java

package com.hdd; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface ProductRepository extends CrudRepository<Product, Long> { List<Product> findByName(String name); }
Code language: PHP (php)

4. @SpringBootApplication trong Spring Boot

Tạo 3 đối tượng vào H2 database và kiểm tra method find().

HddApplication.java

package com.hdd; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HddApplication implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(HddApplication.class); public static void main(String[] args) { SpringApplication.run(HddApplication.class, args); } @Autowired private ProductRepository productRepository; @Override public void run(String... args) { log.info("HddApplication..."); productRepository.save(new Product("Computer")); productRepository.save(new Product("Phone")); productRepository.save(new Product("Book")); System.out.println("\nfindAll()"); productRepository.findAll().forEach(System.out::println); System.out.println("\nfindById(1L)"); productRepository.findById(1l).ifPresent(System.out::println); System.out.println("\nfindByName('Computer')"); productRepository.findByName("Computer").forEach(System.out::println); } }
Code language: JavaScript (javascript)

5. Unit Test

@DataJpaTestTestEntityManager để kiểm tra Spring data JPA repository.

ProductRepositoryTest.java

package com.hdd; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @DataJpaTest public class ProductRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private ProductRepository productRepository; @Test public void testFindByName() { entityManager.persist(new Product("Book1")); List<Product> products = productRepository.findByName("Book1"); Assert.assertEquals(1, products.size()); Assertions.assertThat(products).extracting(Product::getName).containsOnly("Book1"); } }
Code language: JavaScript (javascript)

6. Demo

Mở teminal lên và run câu lệnh sau:

mvn spring-boot:run
Code language: CSS (css)

Kết quả:

findAll() com.hdd.Product@64f3991e [email protected]3bf5911d [email protected]1de30c31 findById(1L) [email protected]238ad211 findByName('Computer') [email protected]92e2c93
Code language: CSS (css)

Như vậy chúng ta đã hiểu sơ qua về Spring Data JPA qua 1 project Spring Boot. Chúc các bạn thành công! 😂

Download source: Github.

Tham khảo 1 số bài viết liên quan:

https://hocspringboot.net/2021/05/25/huong-dan-annotation-query-nativequery-trong-spring-data/

Tài liệu học lập trình: https://codegym.vn/tai-nguyen-hoc-lap-trinh/

Tham khảo khóa học lập trình tại: https://codegym.vn/

COMMENTS:

Leave a Reply

Your email address will not be published. Required fields are marked *