Java Spring Data JPA - 使用标志列的存储库 findAll 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22813539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Data JPA - repository findAll method using flag column
提问by elvisdorow
I want to use the method findAll in a repository, but I`d like it to return just entities which have a certain value. For example, I want it to return just entities which are active = 1. Is there a way to do that?
我想在存储库中使用 findAll 方法,但我希望它只返回具有特定值的实体。例如,我希望它只返回 active = 1 的实体。有没有办法做到这一点?
Now I have to write for all my repositories something like this:
现在我必须为我所有的存储库编写如下内容:
@Query("select p from Parameter p where p.active = 1")
public List<Parameter> findAll();
Instead of using the findOne method I have to write this in all my repositories:
我必须在我所有的存储库中编写它,而不是使用 findOne 方法:
@Query("select p from Parameter p where p.active = 1 and p.id=?1")
public Parameter findById(Long id);
Is there a better way to apply a blanket filter to all queries?
有没有更好的方法将全面过滤器应用于所有查询?
回答by Fabio Maffioletti
If you could consider moving from findAll to another strategy, look at the docs here http://docs.spring.io/spring-data/jpa/docs/1.5.1.RELEASE/reference/html/jpa.repositories.html#jpa.sample-app.finders.strategies
如果您可以考虑从 findAll 转向另一种策略,请查看此处的文档http://docs.spring.io/spring-data/jpa/docs/1.5.1.RELEASE/reference/html/jpa.repositories.html# jpa.sample-app.finders.strategies
The JPA module supports defining a query manually as String or have it being derived from the method name.
JPA 模块支持将查询手动定义为 String 或从方法名称派生。
So in your case if you want to retrieve all entities where active = 1, you can write something like:
因此,在您的情况下,如果您想检索 active = 1 的所有实体,您可以编写如下内容:
public List<Parameter> findByActive(Integer active);
And you can also compose the method name in this way:
您还可以通过这种方式编写方法名称:
public Parameter findByIdAndActive(Long id, Integer active);
The translation between the method signature to the query to be executed is automatic.
方法签名到要执行的查询之间的转换是自动的。
Edit:If you are using boolean for active you can also have methods like
编辑:如果您使用布尔值进行活动,您还可以使用类似的方法
public List<Parameter> findByActiveTrue();
//or
public List<Parameter> findByActiveFalse();