본문 바로가기

JPA DATA TO DTO TO JSON ( Modelmapper & lombock )

java by 낼스 2019. 7. 20.
#### # 참고 - [http://wonwoo.ml/index.php/post/480](http://wonwoo.ml/index.php/post/480) - [https://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html](https://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html) - [https://github.com/Heo-Won-Chul/SpringPersonalProject](https://github.com/Heo-Won-Chul/SpringPersonalProject) - [modelmapper](http://modelmapper.org/) - [허원철의 개발 블로그](http://heowc.tistory.com/65) #### # Spring JPA는 Jackson 라이브러리를 이용한다. - [Jackson Annotation](https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations) - [http://www.baeldung.com/jackson-annotations](http://www.baeldung.com/jackson-annotations) #### # Spring JPA DATA TO DTO TO JSON ( Modelmapper & lombock ) 1. pom.xml 에 등록. ```xml org.projectlombok lombok 1.16.6 org.modelmapper modelmapper 0.7.5 ``` 2. Entity 생성. ```java @Data @Entity @Table(name = "NOTICE") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Notice implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "notice_seq") private Long seq; @NotNull private String title; @NotNull private String content; public Notice() {} public Notice(String title, String content) { this.title = title; this.content = content; } } ``` 3. Repository 생성. ```java @Repository public interface NoticeRepository extends JpaRepository { Notice findBySeq(Integer seq); Page findByTitleContaining(String title, Pageable pageable); Page findByContentContaining(String content, Pageable pageable); } ``` 4. Controller 생성 : @Configuration에 Bean적용. ```java @Bean public ModelMapper modelMapper() { return new ModelMapper(); } @RestController public class NoticeController { @Bean public ModelMapper modelMapper() { return new ModelMapper(); } @Autowired private NoticeRepository noticeRepository; @Autowired private ModelMapper modelMapper; @RequestMapping(value = "/list/{title}/{page}") public Page getNoticeListForTitle(@PathVariable String title,@PathVariable Integer page) { Page noticeList = noticeRepository.findByTitleContaining(title,pageRequestByPage(page)); return noticeList.stream().map(list -> modelMapper.map(list, BasicDTO.GetNoticeList.class)).collect(toList()); } @RequestMapping(value = "/view/{seq}") public BasicDTO.OneNotice getNoticeListForTitle(@PathVariable Integer seq) { Notice data = noticeRepository.findBySeq(seq); return modelMapper.map(data, BasicDTO.OneNotice.class); } } ``` 5. DTO 생성 ```java @Data public class BasicDTO { @Data public static class GetNoticeList{ private list OneNotice } @Data public static class OneNotice{ private Long seq; private String title; private String content; } } ```

댓글