Example: CRUD REST API exposing the Data Transfer Object (DTO) - OrPolyzos/spring-web-initializr GitHub Wiki
Expose a REST API with all the CRUD operations for a User Entity, using a UserDto in the API instead of the User Entity directly.
In all the following code blocks, all the imports, constructors, getters and setters are omitted for brevity
@Entity(name = "user")
public class User implements ResourcePersistable<Long> {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Override
public Long getRpId() {
return this.id;
}
}
public class UserDto {
private Long id;
@NotNull
@NotBlank
private String fullName;
@NotNull
@NotBlank
@Email
private String email;
}
@Repository
public interface UserRepository extends CrudRepository<User, Long> { }
@Service
public class UserDtoService implements RpService<User, Long, UserDto> {
private final UserRepository userRepository;
@Override
public CrudRepository<User, Long> getRepository() {
return userRepository;
}
@Override
public Function<User, UserDto> getEntityToDtoConverter() {
return user -> UserDto.builder()
.id(user.getId())
.fullName(user.getFirstName() + " " + user.getLastName())
.email(user.getEmail())
.build();
}
@Override
public Function<UserDto, User> getDtoToEntityConverter() {
return userDto -> User.builder()
.id(userDto.getId())
.firstName(userDto.getFullName().split(" ")[0])
.lastName(userDto.getFullName().split(" ")[1])
.email(userDto.getEmail())
.build();
}
}
@RequestMapping("/api/user/dto")
@RestController
public class UserDtoRestController implements RpRestController<UserDto, Long> {
private final UserDtoService userDtoService;
@Override
public ResourcePersistableService<UserDto, Long> getService() {
return userDtoService;
}
}
GET - /api/user/dto
GET - /api/user/dto/1
POST - /api/user/dto
{
"fullName": "John Doe",
"email": "[email protected]"
}
PUT - /api/user/dto
{
"id": 1,
"fullName": "John Doe",
"email": "[email protected]"
}
DELETE - /api/user/dto/1