DtoMapper — Data Transfer Object Pattern implementation in Java

DTO

Mapping with DtoMapper

Example

<dependency>
<groupId>com.github.igoricelic</groupId>
<artifactId>dtomapper</artifactId>
<version>1.0.2</version>
</dependency>
public class User {

@Id
private Long id;

private String fullName;

@Column(unique = true)
private String username;

@ManyToMany
private List<Task> tasks;
// constructor, get and set methods
}
public class UserDto {

private Long id;

private String fullName;

private String username;

@Property(depth = 1)
private List<TaskDto> tasks;
// constructor, get and set methods
}
public class Task {

@Id
private Long id;

private String title;

private String description;

private LocalDateTime deadline;

@ManyToOne
@JoinColumn(name = "manager_id")
private User manager;

@ManyToMany(mappedBy = "tasks")
private List<User> employees;
// constructor, get and set methods
}
public class TaskDto {

private Long id;

private String title;

private String description;

private LocalDateTime deadline;

@Property(path = "manager.fullName")
private String manager;

@Property(depth = 1)
private List<UserDto> employees;
// constructor, get and set methods
}
@GetMapping
public Page<UserDto> findAll(Pageable pageable) {
return userService.findAll(pageable);
}

@GetMapping("/{id}")
public UserDto findById(@PathVariable Long id) {
return userService.findById(id);
}
// service dependencies
private final
Mapper mapper;
private final UserDao userDao;

@Override
public Page<UserDto> findAll(Pageable pageable) {
// fetch results from database
Page<User> results = userDao.findAll(pageable);
// map results to desired type and return results as page
return results.map(user -> mapper.map(user, UserDto.class));
}

@Override
public UserDto findById(Long id) {
// fetch user if exists, if doesn't exist -> throw exception
User result = userDao.findById(id)
.orElseThrow(RuntimeException::new);
// map result to desired type with depth
UserDto mappedResult = mapper.map(result, 1, UserDto.class);
// return result
return mappedResult;
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store