spring-data-jpa 如何在SpringDataJPA中基于条件获取数据?

tcomlyy6  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(167)

我的要求是根据某些条件从数据库中提取数据,到目前为止,我已经使用FindAll()和Find()方法完成了提取操作,当从数据库中提取所有记录或单个记录时,这两个方法都很好,但我无法找到任何方法来根据条件提取数据,就像我们在Hibernate标准中所做的那样。
下面是我在Spring Data JPA中的Fetch操作代码:
控制器:

package com.iep.projectentityservice.controller;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.iep.projectentityservice.DTO.ProductDto;
import com.iep.projectentityservice.service.ProductService;

@RestController
@CrossOrigin
public class ProductController 
{
    private static final Logger LOGGER = LogManager.getLogger();

    @Autowired
    ProductService productService;

@GetMapping("/fetchproductdata")
    public ResponseEntity<List<ProductDto>> fetchProductData()
    {
        List<ProductDto> lstProduct = productService.fetchProductData();

        if(lstProduct != null && lstProduct.size() > 0)
        {
            return new ResponseEntity<>(lstProduct,HttpStatus.OK);
        }
        else
        {
            return new ResponseEntity<>(lstProduct,HttpStatus.NOT_FOUND); 
        }
    }
}

服务项目:

package com.iep.projectentityservice.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iep.projectentityservice.DTO.ProductDto;
import com.iep.projectentityservice.blueprint.schema.Products;
import com.iep.projectentityservice.dao.ProductRepository;

@Transactional
@Service
public class ProductServiceImpl implements ProductService
{
    /**The Constant LOGGER. */
    private static final Logger LOGGER = LogManager.getLogger();

    /**The project entity DAO. */
    @Autowired
    ProductRepository productRepository;

@Override
    public List<ProductDto> fetchProductData() 
    {
        LOGGER.info("fetchProductData service called");

        List<ProductDto> lstProduct = null;

        try
        {
            lstProduct = new ArrayList<>();

            List<Products> lstProductDetails = productRepository.findAll();

            if(lstProductDetails != null && lstProductDetails.size() > 0)
            {
                for(int i = 0 ; i < lstProductDetails.size() ; i++)
                {
                    Products product = lstProductDetails.get(i);
                    ProductDto productDto = new ProductDto();

                    productDto.setId(product.getId());
                    productDto.setProductName(product.getProductName());
                    productDto.setDescription(product.getDescription());
                    productDto.setPrice(product.getPrice());
                    productDto.setQuantity(product.getQuantity());

                    lstProduct.add(productDto);
                }
            }
        }
        catch (Exception e) 
        {
            LOGGER.error("Exception in fetchProductData service");
        }
        return lstProduct;
    }
}

储存库:

package com.iep.projectentityservice.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.iep.projectentityservice.blueprint.schema.Products;

public interface ProductRepository extends JpaRepository<Products, Long>{
}

实体:

package com.iep.projectentityservice.blueprint.schema;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "product_details")
public class Products 
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String productName;
    private String description;
    private String price;
    private String quantity;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getQuantity() {
        return quantity;
    }
    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }
}

日期:

package com.iep.projectentityservice.DTO;

public class ProductDto 
{
        private long id;
        private String productName;
        private String description;
        private String price;
        private String quantity;

        public long getId() {
            return id;
        }
        public void setId(long id) {
            this.id = id;
        }
        public String getProductName() {
            return productName;
        }
        public void setProductName(String productName) {
            this.productName = productName;
        }
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public String getPrice() {
            return price;
        }
        public void setPrice(String price) {
            this.price = price;
        }
        public String getQuantity() {
            return quantity;
        }
        public void setQuantity(String quantity) {
            this.quantity = quantity;
        }
}

正如我在代码中所做的那样,获取所有记录,但无法找到一种方法来添加一些限制或标准条件,如在获取时在DataJPA中添加休眠。
那么,有没有办法对SpringDataJPA提取操作添加限制呢?

bd1hkmkf

bd1hkmkf1#

有4个主要选项
1.查询方法命名
1.使用JPQL
1.使用本机查询
1.命名查询
在此处查找其他链接
https://www.baeldung.com/spring-data-jpa-query)(英文)
(http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#存储库。查询方法。查询创建)
(请参阅:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-方法)

public interface ProductRepository extends JpaRepository<Products, Long>{
     //Method Naming convention
     Products findByProductName(String productName);

     //JPQL
     @Query("SELECT p FROM Products p WHERE p.productName = ?1")
     Collection<Products> findAllProductsByName(String productName);

     //Native Query
     @Query(value = "SELECT * FROM Products p WHERE p.productName = ?1", 
     nativeQuery = true)
     Collection<Products> findProductsByName(String productName);
}

相关问题