I have a Spring repository as follows:
import org.springframework.data.repository.Repository;
import org.springframework.stereotype.Component;
import com.te
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.