Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

659
Vistas
In Spring Boot 2, is it possible to auto-generate a JoinTable with a unique constraint?

I'm using Spring Boot 2 and PostGres 10. I have created the following entities, Roles and Privileges,

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

Privilege is

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

Then I have this in my 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}

When my tables are generated, the roles_privileges table is generated like so ...

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)

Are there any other annotations or other Java code I can add so that when my join table is created, the role_id/privilege_id has a unique key generated?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

To force Hibernate to create a primary key with both columns, you have to change 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;
  
}

Autogenerated primary key

over 4 years ago · Santiago Trujillo Denunciar

0

  • You will not see a unique constraint but you will see the following table
   create table roles_privileges (
       role_id binary not null,
       privilege_id binary not null
   )
  • But you can explicitly declare your unique constraint
    @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;
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda