Search code examples
springspring-bootspring-dataspring-data-jpajpql

Creating queries in 3 different ways in spring data JPA


I've got task to create application, which have rest services to attend on CRUD controllers with database.

So: I need to create rest services to bring on spring methods which execute methods from repository (JpaRepository - Spring Data), which create, read, update and delete on invented entity.

The code which "download" data should be in few versions:

  1. creating queries automaticly based on the method name
  2. creating queries defining her with @Query annotation (before method given to repository)
  3. creating queries using method shared by JpaRepository.

And basicly the problem is that I dont understand the question...

Like you can notice here:github I created this using 3rd point (JpaRepository), but I really don't understand how can I create CRUD queries automaticly without using JpaRepository. So my questions are:

  1. This question means that I need to create 3 times CRUD or just add 2 another services to my code?
  2. Can you show me sample how this query should look like in 1st and 2nd point?
  3. In Point 2 I need to use @query, from this spring documentation I know a lot about this annotation, but I don't know if it is possible to create those queries without my interface which expands JpaRepository?

Solution

  • JpaRepository let you 3 choices to manipulate data :

    • default methods (findOne, findAll, ...)
    • implement custom methods (findUserByFirstname, findByAgeOrderByFirstname,...)
    • implement custom method with @query annotation and JPQL ( like SQL)

    So :

    • Version 1 : you implement custom method in you JPA
    • Version 2 : you create custom methods with @query annotation
    • Version 3 : you only use JPA default methods

    In V1 and V2 you logic will be mainly in the JPA implementation. In V3, all your logic will be on the service.

    (If you want to know how JpaRepository works : How are Spring Data repositories actually implemented? )