How to use Constructor Mapping with Spring JPA Repositories

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 18:09:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!