-3

I have a User model which has certain Attributes as depicted below

/**
 * The Class User.
 */
@Entity
@Table(name = "user")
public class User implements UserDetails {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 3961569938206826979L;

    /** The id. */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    /** The first name. */
    private String firstName;

    /** The last name. */
    private String lastName;

    /** The username. */
    @NotNull
    @Size(min = 10, message = "username should have atleast 10 characters")
    private String username;

    /** The password. */
    private String password;

    /** The email. */
    private String email;

    /** The enabled. */
    private boolean enabled;

    /** The last password reset date. */
    private ZonedDateTime lastPasswordResetDate;

    /** The creation date. */
    private ZonedDateTime creationDate;

    /** The phone number. */
    private String phoneNumber;

    private String deviceId;

    /** The authorities. */
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "user_authority", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "authority_id", referencedColumnName = "id"))
    private List<Authority> authorities;

    /**
     * Gets the id.
     *
     * @return the id
     */
    public long getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param id the new id
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * Gets the first name.
     *
     * @return the first name
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * Sets the first name.
     *
     * @param firstName the new first name
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * Gets the last name.
     *
     * @return the last name
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * Sets the last name.
     *
     * @param lastName the new last name
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * Sets the username.
     *
     * @param username the new username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.core.userdetails.UserDetails#getPassword()
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password.
     *
     * @param password the new password
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.security.core.userdetails.UserDetails#getAuthorities()
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.core.userdetails.UserDetails#getUsername()
     */
    @Override
    public String getUsername() {
        return username;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.security.core.userdetails.UserDetails#isAccountNonExpired
     * ()
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.security.core.userdetails.UserDetails#isAccountNonLocked(
     * )
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.core.userdetails.UserDetails#
     * isCredentialsNonExpired()
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.core.userdetails.UserDetails#isEnabled()
     */
    @Override
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Gets the email.
     *
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets the email.
     *
     * @param email the new email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Gets the last password reset date.
     *
     * @return the last password reset date
     */
    public ZonedDateTime getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    /**
     * Sets the last password reset date.
     *
     * @param lastPasswordResetDate the new last password reset date
     */
    public void setLastPasswordResetDate(ZonedDateTime lastPasswordResetDate) {
        this.lastPasswordResetDate = lastPasswordResetDate;
    }

    /**
     * Sets the enabled.
     *
     * @param enabled the new enabled
     */
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    /**
     * Sets the authorities.
     *
     * @param authorities the new authorities
     */
    public void setAuthorities(List<Authority> authorities) {
        this.authorities = authorities;
    }

    /**
     * Gets the creation date.
     *
     * @return the creation date
     */
    public ZonedDateTime getCreationDate() {
        return creationDate;
    }

    /**
     * Sets the creation date.
     *
     * @param creationDate the new creation date
     */
    public void setCreationDate(ZonedDateTime creationDate) {
        this.creationDate = creationDate;
    }

    /**
     * Gets the phone number.
     *
     * @return the phone number
     */
    public String getPhoneNumber() {
        return phoneNumber;
    }

    /**
     * Sets the phone number.
     *
     * @param phoneNumber the new phone number
     */
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "User [id=" + id + ", email=" + email + ", firstName=" + firstName + ", lastName=" + lastName
                + ", password=" + password + ", enabled=" + enabled + ", lastPasswordResetDate=" + lastPasswordResetDate
                + ", authorities=" + authorities + "]";
    }

}

The Authority model has following attributes :

/**
 * The Class Authority.
 */
@Entity
public class Authority implements GrantedAuthority
{

   /** The Constant serialVersionUID. */
   private static final long serialVersionUID = -7546748403961204843L;

   /** The id. */
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;

   /** The name. */
   @Enumerated(EnumType.STRING)
   private UserRoleName name;

   /* (non-Javadoc)
    * @see org.springframework.security.core.GrantedAuthority#getAuthority()
    */
   @Override
   public String getAuthority()
   {
      return name.name();
   }

   /**
    * Gets the id.
    *
    * @return the id
    */
   public long getId()
   {
      return id;
   }

   /**
    * Sets the id.
    *
    * @param id the new id
    */
   public void setId( long id )
   {
      this.id = id;
   }

   /**
    * Gets the roles.
    *
    * @return the roles
    */
   @JsonIgnore
   public UserRoleName getRoles()
   {
      return name;
   }

   /**
    * Sets the roles.
    *
    * @param name the new roles
    */
   public void setRoles( UserRoleName name )
   {
      this.name = name;
   }

   /**
    * Sets the name.
    *
    * @param name the new name
    */
   public void setName( UserRoleName name )
   {
      this.name = name;
   }

   /* (non-Javadoc)
    * @see java.lang.Object#toString()
    */
   @Override
   public String toString()
   {
      return "Authority [id=" + id + ", name=" + name + "]";
   }

}

Now I need to fetch user whose Role is ROLE_ADMIN. So do I first need to fetch the object of Authority having role as ROLE_ADMIN and then call findOneByAuthority, or is there something possible with one function?

I am comming from Django where fetching a record by nested attributes is very simple? Someone can help me in this?

Paras
  • 3,191
  • 6
  • 41
  • 77
  • role is user.authoritie.name? also you are not giving enough information, how are you fetching your data, using spring data? a jdbc?, show us a user query without nested fields if you can =) – Blazerg Jul 29 '19 at 10:59
  • I am using spring data jpa – Paras Jul 29 '19 at 11:25

1 Answers1

0

This will work if you are using Spring Data JPA and you need to create an interface repository where you can define this method.

findByAuthorities(Authority auth)

If this doesn't work, add a query annotation above it and the respective query.

@Query(select u from User left join user_authority ua on u.id = ua.user_id where ua.authority = ?1)

If you want to directly do with the Role enum in Authority entity you can use

findByAuthorities_roleName(RoleEnum role)

And for Query

@Query(select u from User left join user_authority ua on u.id = ua.user_id where ua.authority.role = ?1)

If you want an exact query, please share source code on git/bitbucket.

Access Spring Data JPA reference for above query here https://docs.spring.io/spring-data/data-jpa/docs/2.2.x/reference/html/#jpa.query-methods.query-creation

Aakash Sharma
  • 84
  • 1
  • 5