-
Notifications
You must be signed in to change notification settings - Fork 4
Example: CRUD REST API exposing the Entity
Orestes Polyzos edited this page Jan 3, 2020
·
2 revisions
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
@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;
}
}
@Repository
public interface UserRepository extends CrudRepository<User, Long> { }
@Service
public class UserService implements NoDtoRpService<User, Long> {
private final UserRepository userRepository;
@Override
public CrudRepository<User, Long> getRepository() {
return userRepository;
}
}
@RequestMapping("/api/user")
@RestController
public class UserRestController implements RpRestController<User, Long> {
private final UserService userService;
@Override
public ResourcePersistableService<User, Long> getService() {
return userService;
}
}
GET - /api/user
GET - /api/user/1
POST - /api/user
{
"firstName": "John",
"lastName": "Doe",
"email": "john@doe.com"
}
PUT - /api/user
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"email": "john@doe.com"
}
DELETE - /api/user/1