A simple copy properties wrapper to convert domain into resource/dto and vice versa. Take a look at Ditiow.
Gragle
compile 'com.vidolima:copy-properties-assembler:v1.1.0'
Maven
<dependency>
<groupId>com.vidolima</groupId>
<artifactId>copy-properties-assembler</artifactId>
<version>v1.1.0</version>
<type>pom</type>
</dependency>
My entity class (usually)
@Entity
public class User {
private String firstname;
private String lastname;
private String username;
private String email;
private String birthdate;
// ...
}
User resource with some basics information that all users can see
public class BasicUserResource {
private String firstname;
private String username;
// ...
}
User resource with full information. Only Admin can see
public class FullUserResource {
private String firstname;
private String lastname;
private String username;
private String email;
private String birthdate;
// ...
}
Assembler to convert the domain class (User) into a resource
public class UserAssembler extends GenericResourceAssembler<UserDomain> {
public UserAssembler() {
super(UserDomain.class);
}
}
A rest controller exemplo that converts the User domain to a specific resource
@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_VALUE)
class UserController {
private UserAssembler assembler = new UserAssember();
/** Will return the basic user information. */
@GetMapping(path = "/users/{username}")
public ResponseEntity getBasicUser(@PathVariable String username) {
User domain = this.service.findUserByUsername(username);
BasicUserResource resource = this.assembler.fromDomain(domain, BasicUserResource.class);
return ResponseEntity.ok(resource);
}
/** Will return all the user information (Admin only). */
@GetMapping(path = "/admin/users/{username}")
public ResponseEntity getBasicUser(@PathVariable String username) {
User domain = this.service.findUserByUsername(username);
FullUserResource resource = this.assembler.fromDomain(domain, FullUserResource.class);
return ResponseEntity.ok(resource);
}
}