Search code examples
spring-bootparametersrepositorydtoprojection

Parameters in @Query Annotation for DTO Class Spring Boot 3


I want to use this following DTO-Class to project the Entity-Object in my project in the purpose to retrieve the corresponding information related to my profile depending on id's value given as parameter.

inerface ProfileRepository extends JpaRepository<Profile, Long>{
     //First Option
     @Query("SELECT p FROM Profile p WHERE p.id = ?1")
     Pr_Profile fromEntityToDTO(Long id);
}

And this is my Entity and DTO-Class:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
class Profile{
    private Long id;
    private String login;
    private Strig name;
    private LocalDate birthdate;
}

class Pr_Profile{
    private Long id;
    private String login;
    private LocalDate birthdate;

    public Pr_Profile(int id, String login, LocalDate birthdate){
        this.id = id;
        this.login = login;
        this.birthdate = birthdate;
    }
}     

When I try to retrieve a profile given an id, my Pr_Profile object always remains empty. Instead of a parameter, I tried a number, it worked. After that, I tried with NamedParameter and @Param("id") annotation or with a question mark with and without @Param("id") annotation, it didn't work. Does anyone know more?


Solution

  • The solution is obvious and I missed to annotate the "id" parameter in the controller. Therefore, you just need to declare in the ProfileController, precisely, in the mapping Method a PathParameter Annotation before the id attribute:

    @GetMapping("/api/{id}")
    public String getPage(@PathVariable Long id, Model model){
      //inner Logic
      return "page";
    }