Spring JPA Projection findAll

use*_*040 14 java spring jpql spring-data-jpa

是否可以使用"findAll"为JPARepository返回一个Collection/List of Projections?例:

@Entity
public class Login {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    private Integer id;

    private String name;

    private String pass;

    (...)
Run Code Online (Sandbox Code Playgroud)

}

public interface LoginProjection {
    public String getName();
}

@Repository
public interface LoginRepository extends JpaRepository<Login, Long> {
    Login findByName(String name);

    @Query(value = "SELECT name FROM login", nativeQuery = true)
    List<LoginProjection> findAllLoginProjection();
}
Run Code Online (Sandbox Code Playgroud)

使用@Query它的工作原理!但是不可能使用

 List<LoginProjection> findAll();
Run Code Online (Sandbox Code Playgroud)

因为LoginProjection它没有扩展T(登录).

我在想是否有可能为findAll提供一个"别名",就像findAllXYZ一样,它与findAll做同样的事情.使用过滤器也可以,但我不想使用它们:

 List<LoginProjection> findAllByName(String name);
Run Code Online (Sandbox Code Playgroud)

我的主要目标是这样的:

@Repository
public interface LoginRepository extends JpaRepository<Login, Long> {
    Login findByName(String name);

    List<Login> findAll();

    List<LoginProjection> findAllLoginProjection();
}
Run Code Online (Sandbox Code Playgroud)

这很简单,"零@Query"

Pav*_*nov 20

并向存储库添加一个方法:

List<LoginProjection> findAllProjectedBy();
Run Code Online (Sandbox Code Playgroud)

  • 您所需要的只是“ findBy()”,“ find”和“ By”之间的部分将被查询生成忽略。 (3认同)

t0r*_*r0X 14

我假设您没有使用Spring Data REST,所以@Projection在这里无济于事。@pavel-molchanov 展示了一种表达投影的形式,另一种形式是:

List<LoginProjection> findBy();
Run Code Online (Sandbox Code Playgroud)

如果您有多个投影,则可以通过使用动态投影来避免在存储库中为每个投影创建一个方法,例如:

<T> List<T> findBy(Class<T> projection);

// usage e.g.
... = findBy(LoginProjection.class);
... = findBy(UserSummaryProjection.class);
Run Code Online (Sandbox Code Playgroud)