簡體   English   中英

帶有JPA存儲庫的Spring Boot static where子句

[英]Spring boot static where clause with JPA repositories

我正在研究一個從MySQL DB獲取數據的RESTful Spring Boot項目。

我只想打印所有具有等於1的活動字段的類別,並且要將其應用於CategoryRepository類中的所有方法: findAllfindByParentId

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);



}

我嘗試使用查詢方法,但無法正常工作,並給了我一個例外

如果您將Hibernate用作持久性提供程序,則可以在實體級別使用@Where子句:

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

這將應用於通過持久性提供程序進行的所有查詢。

如果您要使用查詢方法,這可能對您有所幫助

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);
}

@Query批注允許執行本機查詢。 所以,我認為,您應該指定完整的sql如下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM