【问题标题】:Spring security custom user details @Id issueSpring security 自定义用户详细信息@Id 问题
【发布时间】:2021-09-09 12:29:21
【问题描述】:

我目前正在开发一个具有 Spring Security 的 Spring Boot API 来注册和登录。

@Entity
public class Users{

    @Id
    @Column(name = "userid", unique = true, nullable = false)
    public String userid;


    @Email
    @Column(unique = true, nullable = false)
    public String username;

    @JsonProperty(access = JsonProperty.Access.READ_WRITE)
    private String password;

    @Column(columnDefinition = "boolean default true")
    public boolean enabled;

道类

@EnableTransactionManagement
public interface UserDao extends JpaRepository<Users, String> {
    public Users findDistinctByUsername(String username);
}

控制器

Users user = userdao.findDistinctByUsername(username);

当我使用用户名作为@Id 时它工作正常,但如果我使用用户名作为@Id,我会收到错误

错误: org.springframework.orm.jpa.JpaSystemException:通过反射持久属性 [com.example.demo.Model.Users#username] 访问字段 [public java.lang.String com.example.demo.Model.Users.username] 时出错: T1EzQkExUU41Tg;嵌套异常是 org.hibernate.property.access.spi.PropertyAccessException: Error access field [public java.lang.String com.example.demo.Model.Users.username] 通过反射持久属性 [com.example.demo.Model .Users#username] : T1EzQkExUU41Tg",

T1EzQkExUU41Tg: 用户 ID

【问题讨论】:

  • 数据库中用户id的数据类型是什么
  • 用户 ID:Varchar

标签: spring spring-boot hibernate spring-mvc spring-security


【解决方案1】:

当您在 String 上使用 @id 时,您必须指定生成类型,否则它将默认从数据库自动递增为 int。这就是你出错的原因。

@id
private int id;

您必须为字符串属性定义自己的自定义生成器。

@Id
@GeneratedValue(//add the generation type here)
private Long id;

【讨论】:

  • 我在服务级别手动生成Id,这就是为什么我没有使用@GeneratedValue
猜你喜欢
  • 2012-05-23
  • 2017-06-05
  • 2017-12-11
  • 2013-12-13
  • 2011-06-24
  • 2011-01-30
  • 2012-07-20
  • 2013-07-23
  • 2013-03-05
相关资源
最近更新 更多