我正在使用JavaJParepository创建一个Api,我需要在查询中放入一个变量
我想按类别获取产品表中的所有产品。但我不想为所有类别写出查询字符串。我想创建一个可以通过映射传入的变量。我发现实现这一点的唯一方法是通过JPLQ,我正在使用MySQL,我想知道如何将JPLQ语法转换为本机查询 产品存储库我正在使用JavaJParepository创建一个Api,我需要在查询中放入一个变量,java,spring-boot,spring-data-jpa,Java,Spring Boot,Spring Data Jpa,我想按类别获取产品表中的所有产品。但我不想为所有类别写出查询字符串。我想创建一个可以通过映射传入的变量。我发现实现这一点的唯一方法是通过JPLQ,我正在使用MySQL,我想知道如何将JPLQ语法转换为本机查询 产品存储库 import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframew
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import tts.backend.dashboardapi.model.Product;
import java.awt.print.Pageable;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product,Integer> {
@Query("select u from products u where u.category = :category")
List<Product> findByCategory(@Param("category") Integer category);
@Query("select u from products u where u.category = :category AND u.availability = :availability")
List<Product> findByCategoryAndAvailability(@Param("category") Integer category,
@Param("availability")Boolean availability);
我只有一个查询的映射,因为我在运行程序时遇到了一系列异常。你也可以编辑并添加产品模型吗?那些repo方法似乎是,为什么需要@Query?不需要添加注释
@Query(…)
由于Spring JPA提供了支持的查询关键字
您只需删除它们并在方法上组合查询关键字,这样您就可以将findByCategory(整数类别)
only@JonathanJohx当我按照你的建议去做的时候,我在测试它的时候得到了这个错误“映射到“/api/category/1”的处理程序方法不明确,因此您想将上述查询更改为本机查询@拉什米特
@GetMapping("/product/{category}")
public List<Product> findByCategory(@RequestParam (value= "category")Integer category){
return productrepository.findByCategory(category);
}
package tts.backend.dashboardapi.model;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "products")
@EntityListeners(AuditingEntityListener.class)
public class Product implements Serializable{
public Product() {
}
public Product(Integer id, String productName,Category category, double fullPrice, double salePrice, boolean availability, Supplier supplier){
this.id = id;
this.productName = productName;
this.category = category;
this.fullPrice = fullPrice;
this.availablity = availability;
this.supplier = supplier;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "product_name")
private String productName;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name= "category")
private Category category;
@Column(name = "full_price")
private double fullPrice;
@Column(name = "sale_price")
private double salePrice;
@Column(name = "availability")
private boolean availablity;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name = "supplier")
private Supplier supplier;