Example: CRUD REST API exposing the Data Transfer Object (DTO) - OrPolyzos/spring-web-initializr GitHub Wiki

Usage Scenario

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

Implementations

User

@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;
  }
}

UserDto

public class UserDto {

  private Long id;

  @NotNull
  @NotBlank
  private String fullName;

  @NotNull
  @NotBlank
  @Email
  private String email;
}

UserRepository

@Repository
public interface UserRepository extends CrudRepository<User, Long> { }

UserDtoService

@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();
  }
}

UserDtoRestController

@RequestMapping("/api/user/dto")
@RestController
public class UserDtoRestController implements RpRestController<UserDto, Long> {

  private final UserDtoService userDtoService;

  @Override
  public ResourcePersistableService<UserDto, Long> getService() {
    return userDtoService;
  }
}

Request Samples

Read All

GET - /api/user/dto

Read One

GET - /api/user/dto/1

Create

POST - /api/user/dto

{
    "fullName": "John Doe",
    "email": "[email protected]"
}

Update

PUT - /api/user/dto

{
    "id": 1,
    "fullName": "John Doe",
    "email": "[email protected]"
}

Delete

DELETE - /api/user/dto/1

⚠️ **GitHub.com Fallback** ⚠️