【问题标题】:In Spring Boot 2, is it possible to auto-generate a JoinTable with a unique constraint?在 Spring Boot 2 中,是否可以自动生成具有唯一约束的 JoinTable?
【发布时间】:2020-10-12 23:59:21
【问题描述】:

我正在使用 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 代码,以便在创建连接表时生成唯一的角色 ID/特权 ID?

【问题讨论】:

  • 在多对多关系中,role_id 或 privilege_id 不能是唯一的,但它们是复合唯一的
  • 正确——我的情况也是如此。它们是复合独特的。但是,我注意到当我的连接表是自动生成的时,并没有创建这个复合唯一约束。我很好奇根据我的设置是否有办法做到这一点。

标签: spring postgresql spring-boot hibernate join


【解决方案1】:
  • 您不会看到唯一约束,但您会看到下表
   create table roles_privileges (
       role_id binary not null,
       privilege_id binary not null
   )
  • 但您可以显式声明您的唯一约束
    @ManyToMany
    @JoinTable(
       name = "roles_privileges",
       joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
       inverseJoinColumns = @JoinColumn(
                    name = "privilege_id", referencedColumnName = "id"),
       uniqueConstraints = @UniqueConstraint(columnNames = {"role_id", 
                                                        "privilege_id"},
                    name = "rolesPrivilegesConstraint")
    )
    private Collection<Privilege> privileges;

【讨论】:

  • 再次几乎“同时”;)
  • 但答案来自不同的角度。很高兴知道
  • 严格来说,这正是他所要求的,尽管复合主键是更好的长期解决方案 (IMO)。
【解决方案2】:

要强制 Hibernate 为两列创建主键,您必须将 Collection 更改为 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;
  
}

还有:

public class Privilege {
  
  @ManyToMany(mappedBy = "privileges")
  private Set<Role> roles;
  
}

【讨论】:

  • 这是一个比我更好的解决方案
  • 这将是我的首选解决方案(具有复合主键)。但是,请注意,运行时行为会有所不同,具体取决于您是否实现了 equals() / hashCode() 的工作/正确实现。 Set 会简单地忽略向集合重新添加副本(根据您的 equals / hashCode 实现)的请求,而 Collection 会接受重复的元素,然后通过 DB 约束被拒绝。
猜你喜欢
  • 2016-11-21
  • 2020-12-24
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多