如何使用Spring Data JPA从表中的列检索唯一String字段的列表?

时间:2017-09-29 14:17:41

标签: mysql sql performance jpa spring-data-jpa

我有一个包含多行和多列的表格。我想用JpaRepository检索列的所有字段的列表。

我应该写一个查询:

SELECT DISTINCT field2 FROM entity;

使用@Query(QUERY_STRING)

注释该方法

或者使用JPA有更简单的方法吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

如果您需要获取一个字段的值列表,可以执行以下操作:

public interface MyEntityRepo extends JpaRepository<MyEntity, Integer> {

    @Query("select distinct e.field1 from MyEntity e")    
    List<String> getField1Values();
}

如果您需要获取许多字段的值列表,我可以使用dynamic projection向您提出这个技巧:

public interface MyEntityRepo extends JpaRepository<MyEntity, Integer> {

    // T - it's a type of a concrete projection 
    <T extends OneField> List<T> getDistinctBy(Class<T> type);

    default <T extends OneField> List<?> getFieldValues(Class<T> type) {
        return getDistinctBy(type)
               .stream()
               .map(T::getValue)
               .collect(Collectors.toList());
    }
}

// T - it's a type of the table field
public interface OneField<T> {
    default T getValue() {
        return null;
    }
}

然后为您需要获取的值列表的表字段创建投影,并为每个投影调用方法getFieldValues,例如:

public interface Field1 extends OneField<String> {

    @Override
    default String getValue() {
        return getField1();
    }

    String getField1();
}

List<?> values = repo.getFieldValues(Field1.class);

答案 1 :(得分:0)

使用JPA criteria api,类似于:

CriteriaQuery<Entity3450862> criteria = builder.createQuery(Entity3450862.class)
Root root = criteria.from(Entity3450862.class);
Set<Entity3450862> yourDesiredResult = new HashSet<>();
yourDesiredResult.addAll(criteria.select(root.get("T")).list());

应该排序你。此代码未经测试,但应指向正确的方向。