SpringBoot Как найти записи по вложенным атрибутам

У меня есть модель Пользователь с определенными атрибутами, как показано ниже.

/**
 * 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 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 + "]";
   }

}

Теперь мне нужно получить пользователя, чья роль ROLE_ADMIN. Итак, мне сначала нужно получить объект Орган власти, имеющий роль ROLE_ADMIN, а затем вызвать findOneByAuthority, или что-то возможно с одной функцией?

Я пришел из Джанго, где выборка записи по вложенным атрибутам очень проста? Кто-то может помочь мне в этом?

роль user.authoritie.name? также вы не даете достаточно информации, как вы получаете свои данные, используя данные весны? a jdbc?, покажите нам пользовательский запрос без вложенных полей, если можете =)

Blazerg 29.07.2019 12:59

Я использую весенние данные jpa

Paras 29.07.2019 13:25
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
3
2
229
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Это будет работать, если вы используете Spring Data JPA и вам нужно создать репозиторий интерфейса, в котором вы можете определить этот метод.

findByAuthorities(Authority auth)

Если это не работает, добавьте над ним аннотацию запроса и соответствующий запрос.

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

Если вы хотите напрямую работать с перечислением ролей в сущности авторитета, вы можете использовать

findByAuthorities_roleName(RoleEnum role)

И для запроса

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

Если вам нужен точный запрос, поделитесь исходным кодом на git/bitbucket.

Доступ к справочнику Spring Data JPA для вышеуказанного запроса здесь https://docs.spring.io/spring-data/data-jpa/docs/2.2.x/reference/html/#jpa.query-methods.query-creation

если оп хочет искать вложенное поле, то не обязательно искать по всему объекту, вместо этого можно сделать так: findByAuthorities_roleName(String roleName);

Blazerg 29.07.2019 14:22

Согласованный. Добавлено в редактирование.

Aakash Sharma 29.07.2019 16:05

Другие вопросы по теме