简体   繁体   English

Spring JPA中的简单区别

[英]Simple Distinct in Spring JPA

How would you get a list/array of the distinct values in a table using JPA? 您将如何使用JPA获得表中不同值的列表/数组?

Lets say I have an entity and repository of a Foo object from a table that has columns a, b, c. 可以说我有一个具有列a,b,c的表中的Foo对象的实体和存储库。 All I want is to determine all unique(distinct) values in column b where c equals "bar" and have it (the distinct values of b)returned as a list of Strings (not Foo objects). 我要确定的是在b列中确定c等于“ bar”的所有唯一(不同)值,并将其(b的不同值)作为字符串列表(不是Foo对象)返回。

Other ORM's I have found it very simple to do, but I can't seem to figure out how to do this via JPA. 我发现其他ORM的操作非常简单,但我似乎无法弄清楚如何通过JPA进行此操作。 It's a query that's not mapped to an object, but rather just extracting values as a simple list of Strings. 该查询未映射到对象,而是仅将值提取为简单的字符串列表。

Can this be done in JPA, if so, how? 可以在JPA中完成吗?

只需使用以下简单的JPQL查询:

select distinct foo.b from Foo foo where foo.c = 'bar'

query is one way as said by JB Nizet 查询是JB Nizet所说的一种方式

Another way with java8, i would define these methods in repository itself. 用Java8的另一种方式,我将在存储库本身中定义这些方法。 Find distinct Foos and then convert to list of b and return.Call this method with any parameter you want. 查找不同的Foos,然后转换为b的列表并返回。使用所需的任何参数调用此方法。

public interface FooRepository extends CrudRepository.. {
// name this method whatever you want
default List<String> findDistinctbs(final String b) {
    // note following is jpa convention to get list of Foos..
    List<Foo> fooList = findDistinctByb(String b);
    List<String> bList = fooList.stream().map(Foo::getB).collect(Collectors.toList());
    return bList;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM