How to use Constructor Mapping with Spring JPA Repositories

后端 未结 1 839
轻奢々
轻奢々 2021-01-18 18:51

I have a Spring repository as follows:

import org.springframework.data.repository.Repository;
import org.springframework.stereotype.Component;

import com.te         


        
相关标签:
1条回答
  • 2021-01-18 19:16

    I would create a separate class called MyDto which has the JSON stuff, but not the Entity annotations. Make it's fields final as well.

    Then your repository methods would be something like this:

    @Query("SELECT new MyDto(m.code, m.name) FROM My m WHERE m.code = :code")
    public MyDto findByCode(@Param("code") String code);
    

    That way, you are only using the My Entity class to give you the mapping to the database columns, not creating an instance of My.


    EDIT: Another approach (as detailed here) is to use the Entity class itself as the DTO.

    So your query method could look like this:

    @Query("SELECT new My(m.code, m.name) FROM My m WHERE m.code = :code")
    public My findByCode(@Param("code") String code);
    

    This has the advantage of not having to create a separate DTO class.

    0 讨论(0)
提交回复
热议问题