【问题标题】:Spring boot static where clause with JPA repositories带有 JPA 存储库的 Spring Boot 静态 where 子句
【发布时间】:2017-11-30 10:27:13
【问题描述】:

我正在开发一个从 MySQL 数据库中获取数据的 RESTful Spring Boot 项目。

我只想打印所有活动字段等于 1 的类别 我想将其应用于 CategoryRepository 类中的所有方法:findAllfindByParentId ..etc。

package com.userService.repositories;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.userService.entities.Category;

public interface CategoryRepo extends JpaRepository<Category, Integer> {
    @Query("where active =1")
    public List<Category> findByParentId(int id);



}

我尝试使用查询方法但它不起作用并给了我一个异常

【问题讨论】:

    标签: java spring hibernate spring-boot spring-data-jpa


    【解决方案1】:

    如果您使用 Hibernate 作为持久性提供程序,则可以在实体级别利用 @Where 子句:

    @Where(clause = "active =1")
    @Entity
    public  class Category{
    

    这将应用于通过持久性提供程序的所有查询。

    【讨论】:

    • 有没有一种方法可以选择要显示的实体类中的一些属性,而其他的则不显示。
    • 以后要选择active = 0怎么办?
    • 有人注意到@Entity 级别的@Where 条件在我们使用复合键时不适用吗?
    【解决方案2】:

    如果您使用您应该指定的查询方法,这可能会对您有所帮助

    select alias_name from Category c where condition

    from Category where condition

    直接使用方法

    findByActive(int id);

    public interface CategoryRepo extends JpaRepository<Category, Integer> {
        @Query("select c from Category c where c.active =1")
        public List<Category> findByParentId(int id);
    }
    

    【讨论】:

      【解决方案3】:

      @Query 注释允许执行本机查询。所以,我认为,你应该指定完整的sql如下

      @Query("select c from Category c where c.active =1")
      

      【讨论】:

      • 这个查询甚至无法编译。 @Query("SELECT c FROM Category c WHERE c.active = 1")
      • 我已经尝试过了,但它给了我一个异常 => 原因:java.lang.IllegalArgumentException:具有该位置 [1] 的参数不存在
      • 嘿,你在 findByParentId 中传递了 int id。所以,@Query("select c from Category c where c.active =?1") 应该可以工作。 ?1 是一个占位符,将替换为实际的 id
      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2017-05-25
      • 2018-08-06
      • 2012-01-05
      • 2021-04-16
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多