调用此方法:
@EntityGraph(attributePaths = "permissionGroups")
Optional<User> findOneWithPermissionGroupsByLogin(String login);
使用非现有用户登录时,返回null而不是Optional.of(null)
。
我想弄清楚我应该添加什么才能获得一个可选的resault?
更完整的代码:
public interface UserRepository extends JpaRepository<User, Long>
{
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "permissionGroups")
Optional<User> findOneWithPermissionGroupsByLogin(String login);
}
这是相关的用户实体代码
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "euser_permission_group",
joinColumns = @JoinColumn(name="eusers_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="permission_groups_id", referencedColumnName="id"))
private Set<PermissionGroup> permissionGroups = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
//Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = login.toLowerCase(Locale.ENGLISH);
}
public Set<Authority> getAuthorities() {
return authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return login.equals(user.login);
}
@Override
public int hashCode() {
return login.hashCode();
}