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"
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.
The findAll(Pageable pageable) method by default returns a Page<T> object.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With