[英]Spring boot static where clause with JPA repositories
我正在研究一個從MySQL DB獲取數據的RESTful Spring Boot項目。
我只想打印所有具有等於1的活動字段的類別,並且要將其應用於CategoryRepository類中的所有方法: findAll
, findByParentId
。
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.