【问题标题】:What's wrong with my JPQL query?我的 JPQL 查询有什么问题?
【发布时间】:2017-02-25 06:51:36
【问题描述】:

我正在尝试实现加入,但我遇到了错误。我有产品表和商店表。 product表通过外键引用store表如下:

Product.java

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long pId;
    private String model;
    private String brand;
    private byte[] image;
    private Long price;
    private String currency;
    private String transmissionType;
    private String fuelType;

    @ManyToOne
    @JoinColumn(name="storeId")
    private Store store;

    // … getters and setters
}

现在,我展示 Store.java

@Entity
public class Store {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long storeId;
    private String locality;
    private String city;
    private String state;
    private String zipCode;
    private String phone;

    // … getters and setters
}

现在,我展示存储库

public interface ProductRepo extends JpaRepository<Product, Long> {     

    @Query("select p from Product p join p.storeId s where p.storeId = s.storeId and s.city = :city")
    public List<Product> findByCity(@Param("city") String city);

    @Query("select p from Product p join p.storeId s where p.storeId = s.storeId and s.state = :state")
    public List<Product> findByState(@Param("state")  String state);
}

现在,错误是由于我实现连接的最后两个查询造成的。如上所示,我想要做的是获取商店位于特定城市或州的所有产品。

我遇到的错误是:

启动 ApplicationContext 时出错。显示自动配置 报告启用“调试”后重新运行您的应用程序。 2016-10-16 09:53:25.203 错误 16132 --- [主要] os.s.boot.SpringApplication : 应用启动失败

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“catalogueServiceController”的 bean 时出错: 通过字段“productRepo”表示的不满足的依赖关系;嵌套的 例外是 org.springframework.beans.factory.BeanCreationException: 创建名为“productRepo”的 bean 时出错:调用 init 方法 失败的;嵌套异常是 java.lang.IllegalArgumentException: 查询方法 public abstract java.util.List 的验证失败 com.practice.rest.assignment1.repository.ProductRepo.findByCity(java.lang.String)! 等等....

我的查询有什么错误?

【问题讨论】:

    标签: jpa spring-boot spring-data spring-data-jpa jpql


    【解决方案1】:

    查询无效。您指的是不存在的p.storeId。我认为这样的事情就足够了:

    select p from Product where p.store.city = :city
    

    或者:

    select p from Product join p.store as store where store.city = :city
    

    上面应该足够了,因为你的 JPA 提供者应该能够为你做正确的事情。如果您想更具体地了解连接类型以优化查询,则后者可能是首选。

    这同样适用于其他查询。供将来参考:您切断异常堆栈跟踪的所有内容都是有趣的部分 ?。如果持久性提供者拒绝 JPQL,他们通常会非常具体地说明他们遇到的错误。因此,您应该能够在 p.storeId 周围找到一些东西,实际上是在堆栈跟踪更深处的某个地方的无效引用。

    【讨论】:

    • 好的,你的答案是对的,只是你忘了在“Product”和“join”之间添加“p”。查询应该是 select p from Product p join p.store as store where store.city = :city 。休息是正确的。干杯!!
    猜你喜欢
    • 2017-03-07
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2010-12-23
    • 2010-11-26
    相关资源
    最近更新 更多