Skip to content

Example: CRUD REST API exposing the Entity

Orestes Polyzos edited this page Jan 3, 2020 · 2 revisions

Usage Scenario

Expose a REST API with all the CRUD operations for a User Entity.
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;
  }
}

UserRepository

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

UserService

@Service
public class UserService implements NoDtoRpService<User, Long> {

    private final UserRepository userRepository;

    @Override
    public CrudRepository<User, Long> getRepository() {
        return userRepository;
    }
}

UserRestController

@RequestMapping("/api/user")
@RestController
public class UserRestController implements RpRestController<User, Long> {

    private final UserService userService;

    @Override
    public ResourcePersistableService<User, Long> getService() {
        return userService;
    }
}

Request Samples

Read All

GET - /api/user

Read One

GET - /api/user/1

Create

POST - /api/user

{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@doe.com"
}

Update

PUT - /api/user

{
    "id": 1,
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@doe.com"
}

Delete

DELETE - /api/user/1

Clone this wiki locally