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

2024-01-26

我正在使用 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 生成唯一的密钥?


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

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;
  
}

And:

public class Privilege {
  
  @ManyToMany(mappedBy = "privileges")
  private Set<Role> roles;
  
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Spring Boot 2中,是否可以自动生成具有唯一约束的JoinTable? 的相关文章

随机推荐