Model Level Customized Method'Must Override a Superclass Method' Errors after importing a project into EclipseJava: when to use static methodsSort ArrayList of custom Objects by propertyWrongClassException switching from eclipselink to HibernateHow to reference a method in javadoc?Hibernate: ManyToMany inverse DeleteHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?JPA Query for collection map join tablecom.fasterxml.jackson.databind.JsonMappingException: Multiple back-reference properties with name 'defaultReference'How to specify foreign key with the join column?
Can a US President have someone sent to prison?
Why transcripts instead of degree certificates?
How does the Duergar Magic shrink/enlarge ability work with rage?
What exactly is a fey/fiend/celestial spirit?
I hit a pipe with a mower and now it won't turn
Why do user defined scalar functions require the schema?
Symbol for "not absolutely continuous" in Latex
Can the passive "être + verbe" sometimes mean the past?
Which centaur is more 'official'?
What is the difference between handcrafted and learned features
How to solve Keil compiler 'Error: L6218E: Undefined symbol' on STM32
How did researchers use to find articles before the Internet and the computer era?
Generate and graph the Recamán Sequence
Sum of Parts of An Array - JavaScript
Is there reliable evidence that depleted uranium from the 1999 NATO bombing is causing cancer in Serbia?
Was it really unprofessional of me to leave without asking for a raise first?
Avoid using C Strings on C++ code to trim leading whitespace
Loss of majority in Westminster
How would an order of Monks that renounce their names communicate effectively?
What is the line crossing the Pacific Ocean that is shown on maps?
What does Mildred mean by this line in Three Billboards Outside Ebbing, Missouri?
Most elegant way to write a one shot IF
Can another character physically take something that Mage Hand is carrying/holding?
Can you sign using a digital signature itself?
Model Level Customized Method
'Must Override a Superclass Method' Errors after importing a project into EclipseJava: when to use static methodsSort ArrayList of custom Objects by propertyWrongClassException switching from eclipselink to HibernateHow to reference a method in javadoc?Hibernate: ManyToMany inverse DeleteHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?JPA Query for collection map join tablecom.fasterxml.jackson.databind.JsonMappingException: Multiple back-reference properties with name 'defaultReference'How to specify foreign key with the join column?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I developed an authentication service using Spring Cloud Architecture. I need all permission of User, in PrincipleController class, and because of that I implemented a custom method in User entity class.
There are relations between User-Role, User-Permission and Role-Permission entities. I want to know that implementing custom (following getAllPermissions()) method in entity class(I mean implementing model layer) is a bad practice or not ?
package x.y.z.backend.auth.controller;
import x.y.z.backend.auth.model.*;
import x.y.z.backend.auth.service.PermissionService;
import x.y.z.backend.auth.service.PrincipalService;
import x.y.z.backend.auth.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Set;
@RestController
@RequestMapping("/me")
public class PrincipalController
public static final Logger LOG = LoggerFactory.getLogger(PrincipalController.class);
private RoleService roleService;
private PermissionService permissionService;
private PrincipalService principalService;
@Autowired
public PrincipalController(RoleService roleService, PermissionService permissionService, PrincipalService principalService)
this.roleService = roleService;
this.permissionService = permissionService;
this.principalService = principalService;
public PrincipalController()
@GetMapping
public CustomPrincipal principal(Principal principal)
User user = principalService.findByEmail(principal.getName()).get();
Set<Permission> permissions = user.getAllPermissions();
OAuth2Authentication auth = (OAuth2Authentication) principal;
CustomPrincipal customPrincipal = new CustomPrincipal(user.getFirstName(), user.getLastName(), principal.getName(),
auth.getOAuth2Request(), auth.getUserAuthentication(), auth.getAuthorities(), auth.getDetails(), auth.isAuthenticated(),
auth.isClientOnly(), permissions, user.getTenant().getTenantName());
return customPrincipal;
@PutMapping
public User update(@Valid @RequestBody User user, BindingResult bindingResult, Principal principal)
return principalService.update(user, bindingResult, principal);
@PutMapping(path = "/change_password")
public User updatePassword(@Valid @RequestBody UserPassword userPassword, BindingResult bindingResult, Principal principal)
return principalService.updatePassword(userPassword, bindingResult, principal);
@GetMapping(path = "/roles")
public Set<Role> getRoles(Principal principal)
String username = principal.getName();
return roleService.findByEmail(username);
@GetMapping(path = "/permissions")
public Set<Permission> getPermissions(Principal principal)
String username = principal.getName();
return permissionService.findByEmail(username);
package x.y.z.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static x.y.z.backend.auth.enums.Parameter.TENANT_SCHEMA_NAME;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(exclude = "roles", "permissions", "tenant")
@ToString(exclude = "roles", "permissions", "tenant")
@Entity(name = "users")
@Table(schema = TENANT_SCHEMA_NAME)
public class User implements UserDetails
@Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "First name could not be empty")
@Size(min = 2, max = 20, message = "First name must be between min and max characters long")
private String firstName;
@NotNull(message = "Last name could not be empty")
@Size(min = 2, max = 20, message = "Last name must be between min and max characters long")
private String lastName;
@Email(message = "Invalid e-mail address")
@NotNull(message = "E-mail could not be empty")
@Column(unique = true, nullable = false)
@Size(min = 5, max = 100, message = "E-mail must be between min and max characters long")
private String email;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("password")))
@Column(length = 60)
private String password;
@NotNull
private boolean accountNonExpired;
@NotNull
private boolean accountNonLocked;
@NotNull
private boolean credentialsNonExpired;
@NotNull
private boolean enabled;
@Column(nullable = false)
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("roles")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("permissions")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_permissions", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("tenant")))
@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "tenant_users", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id"))
private Tenant tenant;
public User(String firstName, String lastName, String email, String password, boolean accountNonExpired,
boolean accountNonLocked, boolean credentialsNonExpired, boolean enabled,
LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime deletedAt, Set<Role> roles)
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.deletedAt = deletedAt;
this.roles = roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.addAll(roles);
grantedAuthorities.addAll(permissions);
return grantedAuthorities;
public Set<Permission> getAllPermissions()
Set<Permission> allPermissions = new HashSet<>();
allPermissions.addAll(this.permissions);
this.roles.forEach(role -> allPermissions.addAll(role.getPermissions()));
return allPermissions;
@Override
public String getUsername()
return this.getEmail();
java spring spring-boot jpa entity
add a comment |
I developed an authentication service using Spring Cloud Architecture. I need all permission of User, in PrincipleController class, and because of that I implemented a custom method in User entity class.
There are relations between User-Role, User-Permission and Role-Permission entities. I want to know that implementing custom (following getAllPermissions()) method in entity class(I mean implementing model layer) is a bad practice or not ?
package x.y.z.backend.auth.controller;
import x.y.z.backend.auth.model.*;
import x.y.z.backend.auth.service.PermissionService;
import x.y.z.backend.auth.service.PrincipalService;
import x.y.z.backend.auth.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Set;
@RestController
@RequestMapping("/me")
public class PrincipalController
public static final Logger LOG = LoggerFactory.getLogger(PrincipalController.class);
private RoleService roleService;
private PermissionService permissionService;
private PrincipalService principalService;
@Autowired
public PrincipalController(RoleService roleService, PermissionService permissionService, PrincipalService principalService)
this.roleService = roleService;
this.permissionService = permissionService;
this.principalService = principalService;
public PrincipalController()
@GetMapping
public CustomPrincipal principal(Principal principal)
User user = principalService.findByEmail(principal.getName()).get();
Set<Permission> permissions = user.getAllPermissions();
OAuth2Authentication auth = (OAuth2Authentication) principal;
CustomPrincipal customPrincipal = new CustomPrincipal(user.getFirstName(), user.getLastName(), principal.getName(),
auth.getOAuth2Request(), auth.getUserAuthentication(), auth.getAuthorities(), auth.getDetails(), auth.isAuthenticated(),
auth.isClientOnly(), permissions, user.getTenant().getTenantName());
return customPrincipal;
@PutMapping
public User update(@Valid @RequestBody User user, BindingResult bindingResult, Principal principal)
return principalService.update(user, bindingResult, principal);
@PutMapping(path = "/change_password")
public User updatePassword(@Valid @RequestBody UserPassword userPassword, BindingResult bindingResult, Principal principal)
return principalService.updatePassword(userPassword, bindingResult, principal);
@GetMapping(path = "/roles")
public Set<Role> getRoles(Principal principal)
String username = principal.getName();
return roleService.findByEmail(username);
@GetMapping(path = "/permissions")
public Set<Permission> getPermissions(Principal principal)
String username = principal.getName();
return permissionService.findByEmail(username);
package x.y.z.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static x.y.z.backend.auth.enums.Parameter.TENANT_SCHEMA_NAME;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(exclude = "roles", "permissions", "tenant")
@ToString(exclude = "roles", "permissions", "tenant")
@Entity(name = "users")
@Table(schema = TENANT_SCHEMA_NAME)
public class User implements UserDetails
@Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "First name could not be empty")
@Size(min = 2, max = 20, message = "First name must be between min and max characters long")
private String firstName;
@NotNull(message = "Last name could not be empty")
@Size(min = 2, max = 20, message = "Last name must be between min and max characters long")
private String lastName;
@Email(message = "Invalid e-mail address")
@NotNull(message = "E-mail could not be empty")
@Column(unique = true, nullable = false)
@Size(min = 5, max = 100, message = "E-mail must be between min and max characters long")
private String email;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("password")))
@Column(length = 60)
private String password;
@NotNull
private boolean accountNonExpired;
@NotNull
private boolean accountNonLocked;
@NotNull
private boolean credentialsNonExpired;
@NotNull
private boolean enabled;
@Column(nullable = false)
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("roles")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("permissions")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_permissions", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("tenant")))
@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "tenant_users", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id"))
private Tenant tenant;
public User(String firstName, String lastName, String email, String password, boolean accountNonExpired,
boolean accountNonLocked, boolean credentialsNonExpired, boolean enabled,
LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime deletedAt, Set<Role> roles)
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.deletedAt = deletedAt;
this.roles = roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.addAll(roles);
grantedAuthorities.addAll(permissions);
return grantedAuthorities;
public Set<Permission> getAllPermissions()
Set<Permission> allPermissions = new HashSet<>();
allPermissions.addAll(this.permissions);
this.roles.forEach(role -> allPermissions.addAll(role.getPermissions()));
return allPermissions;
@Override
public String getUsername()
return this.getEmail();
java spring spring-boot jpa entity
add a comment |
I developed an authentication service using Spring Cloud Architecture. I need all permission of User, in PrincipleController class, and because of that I implemented a custom method in User entity class.
There are relations between User-Role, User-Permission and Role-Permission entities. I want to know that implementing custom (following getAllPermissions()) method in entity class(I mean implementing model layer) is a bad practice or not ?
package x.y.z.backend.auth.controller;
import x.y.z.backend.auth.model.*;
import x.y.z.backend.auth.service.PermissionService;
import x.y.z.backend.auth.service.PrincipalService;
import x.y.z.backend.auth.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Set;
@RestController
@RequestMapping("/me")
public class PrincipalController
public static final Logger LOG = LoggerFactory.getLogger(PrincipalController.class);
private RoleService roleService;
private PermissionService permissionService;
private PrincipalService principalService;
@Autowired
public PrincipalController(RoleService roleService, PermissionService permissionService, PrincipalService principalService)
this.roleService = roleService;
this.permissionService = permissionService;
this.principalService = principalService;
public PrincipalController()
@GetMapping
public CustomPrincipal principal(Principal principal)
User user = principalService.findByEmail(principal.getName()).get();
Set<Permission> permissions = user.getAllPermissions();
OAuth2Authentication auth = (OAuth2Authentication) principal;
CustomPrincipal customPrincipal = new CustomPrincipal(user.getFirstName(), user.getLastName(), principal.getName(),
auth.getOAuth2Request(), auth.getUserAuthentication(), auth.getAuthorities(), auth.getDetails(), auth.isAuthenticated(),
auth.isClientOnly(), permissions, user.getTenant().getTenantName());
return customPrincipal;
@PutMapping
public User update(@Valid @RequestBody User user, BindingResult bindingResult, Principal principal)
return principalService.update(user, bindingResult, principal);
@PutMapping(path = "/change_password")
public User updatePassword(@Valid @RequestBody UserPassword userPassword, BindingResult bindingResult, Principal principal)
return principalService.updatePassword(userPassword, bindingResult, principal);
@GetMapping(path = "/roles")
public Set<Role> getRoles(Principal principal)
String username = principal.getName();
return roleService.findByEmail(username);
@GetMapping(path = "/permissions")
public Set<Permission> getPermissions(Principal principal)
String username = principal.getName();
return permissionService.findByEmail(username);
package x.y.z.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static x.y.z.backend.auth.enums.Parameter.TENANT_SCHEMA_NAME;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(exclude = "roles", "permissions", "tenant")
@ToString(exclude = "roles", "permissions", "tenant")
@Entity(name = "users")
@Table(schema = TENANT_SCHEMA_NAME)
public class User implements UserDetails
@Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "First name could not be empty")
@Size(min = 2, max = 20, message = "First name must be between min and max characters long")
private String firstName;
@NotNull(message = "Last name could not be empty")
@Size(min = 2, max = 20, message = "Last name must be between min and max characters long")
private String lastName;
@Email(message = "Invalid e-mail address")
@NotNull(message = "E-mail could not be empty")
@Column(unique = true, nullable = false)
@Size(min = 5, max = 100, message = "E-mail must be between min and max characters long")
private String email;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("password")))
@Column(length = 60)
private String password;
@NotNull
private boolean accountNonExpired;
@NotNull
private boolean accountNonLocked;
@NotNull
private boolean credentialsNonExpired;
@NotNull
private boolean enabled;
@Column(nullable = false)
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("roles")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("permissions")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_permissions", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("tenant")))
@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "tenant_users", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id"))
private Tenant tenant;
public User(String firstName, String lastName, String email, String password, boolean accountNonExpired,
boolean accountNonLocked, boolean credentialsNonExpired, boolean enabled,
LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime deletedAt, Set<Role> roles)
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.deletedAt = deletedAt;
this.roles = roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.addAll(roles);
grantedAuthorities.addAll(permissions);
return grantedAuthorities;
public Set<Permission> getAllPermissions()
Set<Permission> allPermissions = new HashSet<>();
allPermissions.addAll(this.permissions);
this.roles.forEach(role -> allPermissions.addAll(role.getPermissions()));
return allPermissions;
@Override
public String getUsername()
return this.getEmail();
java spring spring-boot jpa entity
I developed an authentication service using Spring Cloud Architecture. I need all permission of User, in PrincipleController class, and because of that I implemented a custom method in User entity class.
There are relations between User-Role, User-Permission and Role-Permission entities. I want to know that implementing custom (following getAllPermissions()) method in entity class(I mean implementing model layer) is a bad practice or not ?
package x.y.z.backend.auth.controller;
import x.y.z.backend.auth.model.*;
import x.y.z.backend.auth.service.PermissionService;
import x.y.z.backend.auth.service.PrincipalService;
import x.y.z.backend.auth.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Set;
@RestController
@RequestMapping("/me")
public class PrincipalController
public static final Logger LOG = LoggerFactory.getLogger(PrincipalController.class);
private RoleService roleService;
private PermissionService permissionService;
private PrincipalService principalService;
@Autowired
public PrincipalController(RoleService roleService, PermissionService permissionService, PrincipalService principalService)
this.roleService = roleService;
this.permissionService = permissionService;
this.principalService = principalService;
public PrincipalController()
@GetMapping
public CustomPrincipal principal(Principal principal)
User user = principalService.findByEmail(principal.getName()).get();
Set<Permission> permissions = user.getAllPermissions();
OAuth2Authentication auth = (OAuth2Authentication) principal;
CustomPrincipal customPrincipal = new CustomPrincipal(user.getFirstName(), user.getLastName(), principal.getName(),
auth.getOAuth2Request(), auth.getUserAuthentication(), auth.getAuthorities(), auth.getDetails(), auth.isAuthenticated(),
auth.isClientOnly(), permissions, user.getTenant().getTenantName());
return customPrincipal;
@PutMapping
public User update(@Valid @RequestBody User user, BindingResult bindingResult, Principal principal)
return principalService.update(user, bindingResult, principal);
@PutMapping(path = "/change_password")
public User updatePassword(@Valid @RequestBody UserPassword userPassword, BindingResult bindingResult, Principal principal)
return principalService.updatePassword(userPassword, bindingResult, principal);
@GetMapping(path = "/roles")
public Set<Role> getRoles(Principal principal)
String username = principal.getName();
return roleService.findByEmail(username);
@GetMapping(path = "/permissions")
public Set<Permission> getPermissions(Principal principal)
String username = principal.getName();
return permissionService.findByEmail(username);
package x.y.z.backend.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static x.y.z.backend.auth.enums.Parameter.TENANT_SCHEMA_NAME;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(exclude = "roles", "permissions", "tenant")
@ToString(exclude = "roles", "permissions", "tenant")
@Entity(name = "users")
@Table(schema = TENANT_SCHEMA_NAME)
public class User implements UserDetails
@Transient
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "First name could not be empty")
@Size(min = 2, max = 20, message = "First name must be between min and max characters long")
private String firstName;
@NotNull(message = "Last name could not be empty")
@Size(min = 2, max = 20, message = "Last name must be between min and max characters long")
private String lastName;
@Email(message = "Invalid e-mail address")
@NotNull(message = "E-mail could not be empty")
@Column(unique = true, nullable = false)
@Size(min = 5, max = 100, message = "E-mail must be between min and max characters long")
private String email;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("password")))
@Column(length = 60)
private String password;
@NotNull
private boolean accountNonExpired;
@NotNull
private boolean accountNonLocked;
@NotNull
private boolean credentialsNonExpired;
@NotNull
private boolean enabled;
@Column(nullable = false)
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime deletedAt;
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("roles")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("permissions")))
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "user_permissions", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"))
private Set<Permission> permissions = new HashSet<>(0);
@Getter(onMethod = @__(@JsonIgnore))
@Setter(onMethod = @__(@JsonProperty("tenant")))
@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(schema = TENANT_SCHEMA_NAME, name = "tenant_users", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tenant_id", referencedColumnName = "id"))
private Tenant tenant;
public User(String firstName, String lastName, String email, String password, boolean accountNonExpired,
boolean accountNonLocked, boolean credentialsNonExpired, boolean enabled,
LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime deletedAt, Set<Role> roles)
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.accountNonExpired = accountNonExpired;
this.accountNonLocked = accountNonLocked;
this.credentialsNonExpired = credentialsNonExpired;
this.enabled = enabled;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.deletedAt = deletedAt;
this.roles = roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities()
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
grantedAuthorities.addAll(roles);
grantedAuthorities.addAll(permissions);
return grantedAuthorities;
public Set<Permission> getAllPermissions()
Set<Permission> allPermissions = new HashSet<>();
allPermissions.addAll(this.permissions);
this.roles.forEach(role -> allPermissions.addAll(role.getPermissions()));
return allPermissions;
@Override
public String getUsername()
return this.getEmail();
java spring spring-boot jpa entity
java spring spring-boot jpa entity
edited Mar 25 at 13:31
zackeriya
asked Mar 25 at 12:21
zackeriyazackeriya
356 bronze badges
356 bronze badges
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337680%2fmodel-level-customized-method%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337680%2fmodel-level-customized-method%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown