STACKJAVA

Code ví dụ Spring Data Query Creation (Spring Boot Project)

Code ví dụ Spring Data Query Creation (Spring Boot Project)

Spring Data Query Creation là gì?

Spring Data Query Creation là cơ chế đặt tên method trong interface Repository cho phép sinh ra câu sql tương ứng.

(Xem lại: Query creation trong Spring Data JPA)

Code ví dụ

Các công nghệ sử dụng:

Tạo Database

Tạo database spring-data với table customer trên MySQL

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

Spring Data Query Creation áp dụng cho việc select data nên mình sẽ chỉ tạo project Spring Boot Non-Web để hiển thị kết quả luôn trên console cho đơn giản chứ không thông qua trình duyệt web.

(Xem lại: Code ví dụ Spring Boot Non Web)

Cấu trúc project

File application.properties

Config các thông tin kết nối database, hibernate.

## 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=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect


## ============= LOGGING
logging.pattern.console=

File entity

package stackjava.com.querycreation.entities;

import java.io.Serializable;

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 implements Serializable{
  private static final long serialVersionUID = 1L;

  @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 Repository

Khai báo các method truy vấn, ở đây mình đặt tên theo chuẩn nên không cần khai báo rõ câu sql truy vấn.

Ví dụ:

package stackjava.com.querycreation.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import stackjava.com.querycreation.entities.Customer;

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
    
    List<Customer> findAllByOrderByNameDesc();
    
    List<Customer> findByName(String name);
    
    List<Customer> findByNameAndAddress(String name, String address);
    
    List<Customer> findByNameLike(String name);
    
    List<Customer> findByIdIn(List<Integer> ids);
    
    List<Customer> findByIdLessThan(int index);

}

File chạy ứng dụng

package stackjava.com.querycreation;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Component;

import stackjava.com.querycreation.entities.Customer;
import stackjava.com.querycreation.repository.CustomerRepository;

@SpringBootApplication
@Component
@EnableJpaRepositories
@ComponentScan("stackjava.com")
public class SpringBootDataQueryCreationApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository customerRepository;

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(SpringBootDataQueryCreationApplication.class);
    app.run(args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println("__________Reset and init data________________");
    customerRepository.deleteAll();
    customerRepository.save(new Customer("Dead pool", "Marvel"));
    customerRepository.save(new Customer("Thor", "ragnarok"));
    customerRepository.save(new Customer("Iron Man", "Marvel"));
    customerRepository.save(new Customer("Hulk", "Marvel"));
    customerRepository.save(new Customer("Hawkeye", "Marven"));
    customerRepository.save(new Customer("Thanos", "Titan"));
    customerRepository.save(new Customer("Batman", "DC"));

    System.out.println("__________Demo find all order by name desc________________");
    List<Customer> listCustomer1 = customerRepository.findAllByOrderByNameDesc();
    for (Customer customer : listCustomer1) {
      System.out.println(customer);
    }
    System.out.println("__________Demo find find by name like 'th'________________");
    List<Customer> listCustomer2 = customerRepository.findByNameLike("%th%");
    for (Customer customer : listCustomer2) {
      System.out.println(customer);
    }
  }

}

Demo + Kết quả

Code ví dụ Spring Data Query Creation (Spring Boot Project) stackjava.com

Okay, Done!

Download code ví dụ trên tại đây.

 

References.

https://docs.spring.io/spring-data/…/jquery-methods.query-creation

https://docs.spring.io/spring-data/…/jpa.repositories.html