gpt4 book ai didi

java - Spring Boot JPA如何实现用户和权限表之间的外键?

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:39 24 4
gpt4 key购买 nike

如果这是一个显而易见的问题,请原谅我。

我的应用程序使用 LDAP 身份验证,但从其数据库加载用户权限,效果非常好。现在,我尝试创建 JPA 实体来通过 REST 接口(interface)管理用户和权限。

如何使用 JPA 实现以下架构?

create table users(
username varchar(50) not null primary key,
password varchar(50) not null,
enabled boolean not null
);

create table authorities (
username varchar(50) not null,
authority varchar(50) not null,
constraint fk_authorities_users foreign key(username) references users(username)
);

create unique index ix_auth_username on authorities (username, authority)
<小时/>

这是我迄今为止创建的:

User.java:

@Entity
@Data
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
public class User {
@Id
@NotNull
@Column(length=50)
private String username;

@NotNull
private String password;

@NotNull
boolean enabled;
}

Authority.java:

@Entity
@Data
@Table(name = "authorities", uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
public class Authority {
@Id
@NotNull
@Column(length=50)
private String username;

@NotNull
private String authority;
}

用户存储库:

public interface UserRepository extends CrudRepository<User, Long> { }

最佳答案

使用JPA注释manyToOne和oneToMany:

User.java

@Entity
@Data
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
public class User {
@Id
@NotNull
@Column(length=50)
private String username;

@NotNull
private String password;

@NotNull
boolean enabled;

@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = false)
private List<Authority> listAuthorities = new ArrayList<>();

}

Authority.java

@Entity
@Data
@Table(name = "authorities", uniqueConstraints = {@UniqueConstraint(columnNames = {"username"})})
public class Authority {

@Id
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user.username")
private User user;

@NotNull
private String authority;
}

关于java - Spring Boot JPA如何实现用户和权限表之间的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52004135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com