Spring Boot如何通过嵌套属性查找记录[重复]

Posted

技术标签:

【中文标题】Spring Boot如何通过嵌套属性查找记录[重复]【英文标题】:SpringBoot How to find records by nested attributes [duplicate] 【发布时间】:2019-12-06 16:55:47 【问题描述】:

我有一个 用户 模型,它具有如下所示的某些属性

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


Authority 模型具有以下属性:

/**
 * 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 角色的 Authority 对象,然后调用 findOneByAuthority,或者是否有可能使用一个函数?

我来自 Django,通过嵌套属性获取记录非常简单? 有人可以帮助我吗?

【问题讨论】:

角色是user.authority.name?你也没有提供足够的信息,你是如何使用弹簧数据获取数据的?一个 jdbc?,如果可以的话,向我们展示一个没有嵌套字段的用户查询 =) 我使用的是spring data jpa 【参考方案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

【讨论】:

如果op要查找嵌套字段,不必按整个对象查找,可以这样:findByAuthorities_roleName(String roleName); 同意。在编辑中添加。

以上是关于Spring Boot如何通过嵌套属性查找记录[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot如何通过查找表将两个实体嵌套在一起而返回另一个实体?

Spring数据,通过嵌套对象的属性查找

spring-boot骆驼案例嵌套属性作为环境变量

Spring数据,通过嵌套对象的属性查找

如何解决 java spring boot 应用程序中的安全审计查找日志注入

如何在 bean 实例化之前记录 Spring Boot 应用程序的所有活动属性?