我是Spring Boot的新手。 我尝试使用Spring Security和Hibernate实现登录和注册功能。
首先,我使用Hibernate从数据库生成持久性映射Entity Class。而且我需要在UserEntity类中实现UserDetails接口,但是问题发生了。
我无法在UserDetails中实现方法。
当我尝试实现getAuthorities时发生错误。 这是错误信息。
“基本”属性类型不应为容器。 检查信息:此检查检查以下JPA规范错误:
对于基于属性的访问,应该同时存在setter和getter 检查信息:此检查检查以下JPA规范错误:
这是我的代码。
package com.example.demo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "user", schema = "demo", catalog = "")
public class UserEntity implements UserDetails {
private String username;
private String password;
private String role;
private String nickname;
private String phone;
@Override
public Collection<? extends GrantedAuthority> getAuthorities(){
String[] authorities=role.split(",");
List<SimpleGrantedAuthority> authorityList=new ArrayList<>();
for(String string:authorities)
authorityList.add(new SimpleGrantedAuthority(string));
return authorityList;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Id
@Column(name = "username", nullable = false, length = 16)
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "password", nullable = true, length = 32)
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Basic
@Column(name = "nickname", nullable = true, length = 32)
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Basic
@Column(name = "phone", nullable = true, length = 11)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
return Objects.equals(username, that.username) &&
Objects.equals(password, that.password) &&
Objects.equals(nickname, that.nickname) &&
Objects.equals(phone, that.phone);
}
@Override
public int hashCode() {
return Objects.hash(username, password, nickname, phone);
}
}
我创建了与UserEntity完全相同的类,并实现了UserDetails,问题消失了。也许这有点愚蠢,但我已经尝试了很多次。我解决不了请帮忙。
答案 0 :(得分:0)
尝试使用@OneToMany
或@Transient
而不是@Basic
批注。
答案 1 :(得分:0)
在JPA中,当一个对象引用另一个对象或对象组时,应指定两者之间的关系。例如:
@Entity
class Parent {
// you should tell the JPA how to treat this collection
Set<Child> children
}
如@Zon所述,您可以跳过将其保存(@Transient)或将子级另存为另一个实体并定义两者之间的关系(@oneToMany)或您忽略它(@transient)或将其保存为Binay格式作为斑点(@Lob)。