2016-11-04 29 views
0

如何使用JPA獲取表中不同值的列表/數組?在Spring中簡單明瞭JPA

可以說,我有一個實體和Foo對象的存儲庫從一個表中有列a,b,c。我想要的是確定列b中的所有唯一(不同的)值,其中c等於「bar」,並將它作爲字符串列表(而不是Foo對象)返回(b的不同值)。

其他ORM的我發現它很簡單,但我似乎無法弄清楚如何通過JPA做到這一點。這是一個沒有映射到對象的查詢,而只是將值提取爲一個簡單的字符串列表。

這可以在JPA中完成嗎?如果是這樣,怎麼辦?

+0

的可能的複製[如何找到字段列表使用JPA和Spring重複行?(http://stackoverflow.com/questions/32079084/how-to-find-distinct-rows-with-字段在列表中使用jpa和彈簧) – DimaSan

回答

0

只要使用這個簡單的JPQL查詢:

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

這是我第一次嘗試。你介意給整個結構提供註釋和方法簽名嗎? – FiguringThisOut

+0

'@Query(「select foo.b from foo foo where foo.c ='bar'」)列表 whateverNameYouWant();' –

+0

這正是我所追求的,但我得到:**無法解析屬性: b:com.bar.entity.Foo [從com.bar.entity.Foo中選擇不同的foo.b,其中foo.c =?1] ** – FiguringThisOut

0

查詢按JB Nizet

與java8另一種方式說一個辦法,我會定義庫本身這些方法。找到不同的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; 
}