问题是h2只存储我的类User的属性,但无法存储Spring Security的User类的属性用户名,密码和权限。
以下是我的用户类:
package com.netcetera.videoverification.persistence.model;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.*;
import java.util.Collection;
@Entity
@Table(name = "user")
@Setter
@Getter
public class User extends org.springframework.security.core.userdetails.User {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String email;
private String firstName;
private String lastName;
public User(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public User(String username, String password, Collection<? extends GrantedAuthority> authorities, String email,
String firstName, String lastName) {
super(username, password, authorities);
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
}
存储库的代码:
package com.netcetera.videoverification.persistence.repository;
import com.netcetera.videoverification.persistence.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends CrudRepository<User,Long> {
}
这是服务:
package com.netcetera.videoverification.service;
import com.netcetera.videoverification.persistence.model.User;
import com.netcetera.videoverification.persistence.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public boolean create(String username, String email, String password) {
String passwordHash = new BCryptPasswordEncoder().encode(password);
Collection<GrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
User user = new User(username, passwordHash, authorities, email, "First", "Last");
this.userRepository.save(user);
return true;
}
}
数据库条目的屏幕截图: DB entries screenshot
答案 0 :(得分:1)
这种情况正在发生,因为hibernate没有看到继承的字段,因为超类没有标注@MappedSuperclass
注释。
您可能会尝试将休眠访问模式从字段切换到属性,但由于org.springframework.security.core.userdetails.User
中的密码字段为private
,因此根本没有设置者,而其他字段为{{1}这使得hibernate无法以任何方式更新它们。
我建议您不要自己扩展private final
创建org.springframework.security.core.userdetails.User
,username
和password
字段,如果需要通过,则只需实现roles
接口这个类的一个实例在其他地方(其中spring security userdetails object is expected)。