Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA Projection findAll

Tags:

Is it possible to use "findAll" for a JPARepository returning a Collection/List of Projections? Example:

@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;      (...) 

}

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

Using @Query it works! But it is not possible to use

 List<LoginProjection> findAll(); 

Because LoginProjection it does not extends T (Login).

I was thinking if it is possible to give a "alias" for findAll like findAllXYZ that does the same thing as findAll. Using filters it works too, but I do not want to use them:

 List<LoginProjection> findAllByName(String name); 

My main goal would be something like this:

@Repository public interface LoginRepository extends JpaRepository<Login, Long> {     Login findByName(String name);      List<Login> findAll();      List<LoginProjection> findAllLoginProjection(); } 

Which is pretty easy and with "zero @Query"

like image 385
user3558040 Avatar asked Jun 15 '18 16:06

user3558040


People also ask

What is findAll in Spring JPA?

The Iterable<T> findAll() method returns all entities that are saved to the database. The T findOne(Long id) method returns the entity whose id is given as method parameter. If no entity is found, this method returns null.

What does JPA findAll return?

The findAll(Pageable pageable) method by default returns a Page<T> object.

What is projection in Spring JPA?

Projection is one of the first things you're probably thinking about when implementing a query with Spring Data JPA. This is because projection defines the entity attributes and the database columns returned by your query. So, selecting the right columns is important for your business logic.

How do you fetch a one to many DTO projection with JPA and Hibernate?

Fetching a one-to-many DTO projection with JPA and Hibernate. The postDTOMap is where we are going to store all PostDTO entities that, in the end, will be returned by the query execution. The reason we are using the postDTOMap is that the parent rows are duplicated in the SQL query result set for each child record.


1 Answers

And add a method to the repository:

List<LoginProjection> findAllProjectedBy(); 

The method name can be simplified to findBy() to match the documentation example at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

like image 138
Pavel Molchanov Avatar answered Sep 20 '22 12:09

Pavel Molchanov