gpt4 book ai didi

spring - 在 Spring Boot 2 中,是否可以自动生成具有唯一约束的 JoinTable?

转载 作者:行者123 更新时间:2023-12-04 01:21:46 37 4
gpt4 key购买 nike

我正在使用 Spring Boot 2 和 PostGres 10。我创建了以下实体、角色和权限,

@Data
@Entity
@Table(name = "Roles")
public class Role {

public enum Name {
USER,
ADMIN
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;

@Column(unique=true)
@Enumerated(EnumType.STRING)
private Name name;

@ManyToMany
@JoinTable(
name = "roles_privileges",
joinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
}

特权是

@Data
@Entity
@Table(name = "Privileges")
public class Privilege {

public enum PrivilegeName {
SUPER_ADMIN,
USER
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;

@Column(unique=true)
@Enumerated(EnumType.STRING)
private PrivilegeName name;

@ManyToMany(mappedBy = "privileges")
private Collection<Role> roles;
}

然后我在我的 application.properties 中有这个

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.show-sql=true

spring.datasource.url=jdbc:postgresql://${PG_DB_HOST:localhost}:5432/${PG_DB_NAME}

spring.datasource.username=${PG_DB_USER}
spring.datasource.password=${PG_DB_PASS}

当我的表生成时,roles_privileges 表是这样生成的......

cardmania=# \d roles_privileges ;
Table "public.roles_privileges"
Column | Type | Modifiers
--------------+------+-----------
role_id | uuid | not null
privilege_id | uuid | not null
Foreign-key constraints:
"fk5duhoc7rwt8h06avv41o41cfy" FOREIGN KEY (privilege_id) REFERENCES privileges(id)
"fk629oqwrudgp5u7tewl07ayugj" FOREIGN KEY (role_id) REFERENCES roles(id)

是否可以添加任何其他注释或其他 Java 代码,以便在创建连接表时,role_id/privilege_id 生成一个唯一的 key ?

最佳答案

要强制 Hibernate 创建包含两列的主键,您必须通过 Set 更改 Collection

public class Role {

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "roles_privileges",
joinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Set<Privilege> privileges;

}

和:

public class Privilege {

@ManyToMany(mappedBy = "privileges")
private Set<Role> roles;

}

Autogenerated primary key

关于spring - 在 Spring Boot 2 中,是否可以自动生成具有唯一约束的 JoinTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62526030/

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