seon99il

Java

How to use builders efficiently when mapping Dto, Entity

2 min read

SpringBoot : 2.7.5 Java : 11

Overview

Request to Dto, Entity to Dto. When we develop with Java, the same data is passed and received through multiple classes. If you use JPA to get data from the DB, you will basically use about 3 classes: Entity, Dto, and Request/Response.

We get the Entity class from the DB, convert the Entity to a Dto in the service layer, and finally convert the Dto to a response and return it. Insertion is similar: req → dto → entity.

How do you prefer to do these conversions? There are many ways to do this, but I mostly like and prefer using the builder pattern.

However, this too is somewhat vulnerable to change. Let’s start with a simple example.

Classes (Entity, Dto, Res)

I will only explain the process of converting entity to dto, because they are mapped in the same way.

public class PostEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long postSeq;

    @Column(name = "POST_TITLE")
    private String postTitle;

    @Column(name = "POST_CONTENT")
    private String postContent;

    @Column(name = "CREATE_DATE")
    private Date createDate;
}
@Getter
@Builder
@RequiredArgsConstructor
public class PostDto {
    private final Long postSeq;
    private final String postTitle;
    private final String postContent;
    private final Date createDate;
}
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
    private final PostRepository postRepository;

    @Transactional(readOnly = true)
    public PostDto findPostById(long postSeq) throws Exception {
        final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
                -> new NoSuchElementException("cannot found post info with id : " + postSeq));

        return PostDto.builder()
                .postSeq(post.getPostSeq())
                .postTitle(post.getPostTitle())
                .postContent(post.getPostContent())
                .createDate(post.getCreateDate())
                .build();
    }
}

If you use the Builder pattern, you will convert Entity to Dto in this way. But let’s think about it. What if one column is added to PostEntity?

    @Column(name = "CREATE_BY")
    private String createBy;

We have to take several actions.

  1. Add the same column in the Dto
  2. Add the new column everywhere the builder is used
@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
    private final PostRepository postRepository;

    @Transactional(readOnly = true)
    public PostDto findPostById(long postSeq) throws Exception {
        final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
                -> new NoSuchElementException("cannot found post info with id : " + postSeq));

        return PostDto.builder()
                ~~~
                .createBy(post.getCreateBy())
                .build();
    }
}

Here comes the problem. How many methods do I have to change? Where was it used?

To solve this problem, we can use a static method when converting an entity to a dto.

@Getter
@Builder
@RequiredArgsConstructor
public class PostDto {
    private final Long postSeq;
    private final String postTitle;
    private final String postContent;
    private final Date createDate;
    private String createBy;

    public static PostDto ofEntity(PostEntity entity) {
        return PostDto.builder()
                .postSeq(entity.getPostSeq())
                .postTitle(entity.getPostTitle())
                .postContent(entity.getPostContent())
                .createDate(entity.getCreateDate())
                .createBy(entity.getCreateBy()).build();
    }
}

Declare an of method as static in the Dto, and you can use this method when converting Entity to Dto in the service.

    @Transactional(readOnly = true)
    public PostDto findPostById(long postSeq) throws Exception {
        final PostEntity post = postRepository.findById(postSeq).orElseThrow(()
                -> new NoSuchElementException("cannot found post info with id : " + postSeq));

        return PostDto.ofEntity(post);
    }

In this case, in the same situation as before, you only have to add the new column to the static method in the Dto.

It is also more efficient when converting lists.

@Slf4j
@Service
@RequiredArgsConstructor
public class PostService {
    private final PostRepository postRepository;

    @Transactional(readOnly = true)
    public List<PostDto> findAllPost() throws Exception {
        return postRepository.findAll().stream().map(PostDto::ofEntity)
                .collect(Collectors.toList());
    }
}

This method is very simple and efficient.

Previous posts

View all posts →

Comments