Spring Data JPA查询方法-IN子句

x33g5p2x  于2022-10-13 转载在 Spring  
字(7.9k)|赞(0)|评价(0)|浏览(3103)

在本教程中,我们将学习如何在SpringDataJPA存储库中为In子句条件编写查询方法。
SpringDataJPA查询方法是最强大的方法,我们可以创建查询方法来从数据库中选择记录,而无需编写SQL查询。在幕后,SpringDataJPA将基于查询方法创建SQL查询,并为我们执行查询。
让我们按照SpringDataJPA命名约定为Product实体类的IN子句编写一个查询方法。
我们需要创建一个方法,从前缀findBy开始,后跟字段名,然后是In后缀**-findBy[FieldName][In]**
示例:考虑Product实体类,如果我们想使用In子句检索产品,那么这里是Spring Data JPA查询方法:

List<Product> findByNameIn(List<String> names);

让我们创建一个完整的示例来了解端到端。

Maven依赖项

创建一个Spring引导项目,并向其添加以下maven依赖项:

<?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.6.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>net.javaguides</groupId>
	<artifactId>spring-data-jpa-course</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-data-jpa-course</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

产品实体

让我们首先创建一个Product实体类,并向其中添加以下内容:

package net.javaguides.springdatajpacourse.entity;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

@Entity
@Table(name="products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "sku")
    private String sku;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "image_url")
    private String imageUrl;

    @Column(name = "active")
    private boolean active;

    @Column(name = "date_created")
    @CreationTimestamp
    private Date dateCreated;

    @Column(name = "last_updated")
    @UpdateTimestamp
    private Date lastUpdated;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public Date getLastUpdated() {
        return lastUpdated;
    }

    public void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", sku='" + sku + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", imageUrl='" + imageUrl + '\'' +
                ", active=" + active +
                ", dateCreated=" + dateCreated +
                ", lastUpdated=" + lastUpdated +
                '}';
    }
}

产品存储库

让我们创建扩展JpaRepositoryProductRepository,并向其添加以下代码:

import java.util.List;

import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
	/**
	 * Return the products based on SQL in clause condition
	 * @param names
	 * @return
	 */
	List<Product> findByNameIn(List<String> names);
}

配置MySQL和Hibernate属性

在本例中,让我们使用MySQL数据库存储和检索数据,并使用Hibernate属性创建和删除表。
打开application.properties文件并向其中添加以下配置:

spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

spring.jpa.hibernate.ddl-auto = create-drop

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

在运行Spring引导应用程序之前,请确保您将创建电子商务数据库。
此外,根据您机器上的MySQL安装更改MySQL用户名和密码。

测试Spring数据JPA查询方法-IN子句

为了用我们创建的In子句测试查询方法,我们将在Spring引导应用程序启动时使用CommandLineRunner.run()方法执行测试代码:

import net.javaguides.springdatajpacourse.entity.Product;
import net.javaguides.springdatajpacourse.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@SpringBootApplication
public class SpringDataJpaCourseApplication implements CommandLineRunner{

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringDataJpaCourseApplication.class, args);
	}

	@Autowired
	private ProductRepository productRepository;

	@Override
	public void run(String... args) throws Exception {
        Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setDateCreated(new Date());
        product.setLastUpdated(new Date());
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");

        // save product
        productRepository.save(product);

        Product product2 = new Product();
        product2.setName("product 2");
        product2.setDescription("product 2 desc");
        product2.setPrice(new BigDecimal(200));
        product2.setDateCreated(new Date());
        product2.setLastUpdated(new Date());
        product2.setSku("product 2 sku");
        product2.setActive(true);
        product2.setImageUrl("product2.png");

        // save product 2
        productRepository.save(product2);

        // products based on in condition
        List<Product> productsIn = productRepository.findByNameIn(List.of("product 1","product 2"));
        productsIn.forEach((p) ->
                System.out.println(p));
	}
}


Spring引导应用程序执行完成后,您可以在控制台中看到Spring Data JPA(使用Hibernate作为JPA提供程序)生成的SQL语句:

Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        products
        (active, date_created, description, image_url, last_updated, name, price, sku) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    select
        product0_.id as id1_0_,
        product0_.active as active2_0_,
        product0_.date_created as date_cre3_0_,
        product0_.description as descript4_0_,
        product0_.image_url as image_ur5_0_,
        product0_.last_updated as last_upd6_0_,
        product0_.name as name7_0_,
        product0_.price as price8_0_,
        product0_.sku as sku9_0_ 
    from
        products product0_ 
    where
        product0_.name in (
            ? , ?
        )

请注意,以下带有In子句的SQL查询:

select
        product0_.id as id1_0_,
        product0_.active as active2_0_,
        product0_.date_created as date_cre3_0_,
        product0_.description as descript4_0_,
        product0_.image_url as image_ur5_0_,
        product0_.last_updated as last_upd6_0_,
        product0_.name as name7_0_,
        product0_.price as price8_0_,
        product0_.sku as sku9_0_ 
    from
        products product0_ 
    where
        product0_.name in (
            ? , ?
        )

相关文章

微信公众号

最新文章

更多