반응형

DTO 인터페이스

public interface DTO<T extends Domain, Y extends DTO> {
    Y getInstanceByEntity(T t);
    T toEntity();
}

DTO 구현체

@Getter
@Setter
public class NoticeDTO implements DTO<Notice, NoticeDTO> {

    private Long pkey;
    private String title;
    private String content;
    private Long createdDt = new Date().toInstant().getEpochSecond(); // Instant

    public NoticeDTO() {
    }

    public NoticeDTO(Notice notice) {
        this.pkey = notice.getPkey();
        this.title = notice.getTitle();
        this.content = notice.getContent();
        this.createdDt = notice.getCreatedDt().getEpochSecond();
    }

    @Override
    public NoticeDTO getInstanceByEntity(Notice notice) {
    	NoticeDTO noticeDTO = new NoticeDTO(notice);
        return noticeDTO;
    }


    @Override
    public Notice toEntity() {
        return Notice.builder()
            .pkey(this.pkey)
            .title(this.title)
            .content(this.content)
            .createdDt(Instant.ofEpochSecond(this.createdDt))
            .build();

    }

}

 

Entity 인터페이스 

public interface Domain {

}

Entity 구현체

@Entity
@Table(name = "Notice")
@Getter @ToString
public class Notice implements Domain {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long pkey;
    private String title;
    private String content;
    private Instant createdDt;

    public Notice() {
    }

    @Builder
    public Notice(Long pkey, String title, String content,
                  Instant createdDt) {
        this.pkey = pkey;
        this.title = title;
        this.content = content;
        this.createdDt = createdDt;
    }
}

 

Page<Entity> -> List<DTO> 변환 util

public class DataSourceUtils {

    private DataSourceUtils() {
    }

    public static <Y extends Domain, T extends DTO<Y, T>> List<T> convertEntityToDTOList(Page<Y> page, T t) {
        List<Y> content = page.getContent();
        return content.stream().map(x -> t.getInstanceByEntity(x)).collect(Collectors.toList());
    }

}
Page<Notice> page = noticeRepository.findAllByCode(code, pageable);
List<NoticeDTO> list = DataSurceUtils.convertEntityToDTOList(page, new NoticeDTO());
반응형

+ Recent posts