简体   繁体   中英

Simple Distinct in Spring JPA

How would you get a list/array of the distinct values in a table using JPA?

Lets say I have an entity and repository of a Foo object from a table that has columns a, b, c. 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).

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. 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?

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

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

query is one way as said by JB Nizet

Another way with java8, i would define these methods in repository itself. Find distinct Foos and then convert to list of b and return.Call this method with any parameter you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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