Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

583
Visualizações
How can I use an UUID as an @Id for my @Entity properly?

I want to store a User entity from Spring Boot into a MySQL database and I want to use an UUID as an Id. But when I follow the online solutions I only get The userId doesn't have a default value. And I just can't figure out whats wrong. Here is the code:

User entity:

@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
@Data
public class User {

    @JsonProperty("userId")
    @Column(name = "userId", columnDefinition = "BINARY(16)")
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Id
    private UUID userId;
    
    @JsonProperty("email")
    @Column(name = "email", nullable = false)
    private String email;
    
    @JsonProperty("name")
    @Column(name = "name", nullable = false)
    String name;

    @JsonProperty("surname")
    @Column(name = "surname", nullable = false)
    String surname;

    @JsonProperty("password")
    @Column(name = "password", nullable = false)
    private String password;
}

MySQL table:

create table if not exists user (
   userId binary(16) not null primary key,
   name varchar(80) not null,
   surname varchar(80) not null,
   email varchar(120) not null,
   password varchar(120) not null
);

The error message:

SQL Error: 1364, SQLState: HY000

2020-07-23 15:31:29.234 ERROR 16336 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : Field 'userId' doesn't have a default value
2020-07-23 15:31:29.251 ERROR 16336 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

First of all I have to notice that:

According to JPA only the following types should be used as identifier attribute types:

  • any Java primitive type
  • any primitive wrapper type
  • java.lang.String
  • java.util.Date (TemporalType#DATE)
  • java.sql.Date
  • java.math.BigDecimal
  • java.math.BigInteger

Any types used for identifier attributes beyond this list will not be portable.

But, Hibernate supports UUID identifier value generation. This is supported through its org.hibernate.id.UUIDGenerator id generator.

You can use the default strategy, that is a version 4 (random) strategy according to IETF RFC 4122.

@Id
@Column(name = "userId", columnDefinition = "BINARY(16)")
@GeneratedValue
private UUID userId;

Or an alternative strategy which is a RFC 4122 version 1 (time-based) strategy (using IP address rather than mac address).

@Id
@Column(name = "userId", columnDefinition = "BINARY(16)")
@GeneratedValue(generator = "custom-uuid")
@GenericGenerator(
    name = "custom-uuid",
    strategy = "org.hibernate.id.UUIDGenerator",
    parameters = {
        @Parameter(
            name = "uuid_gen_strategy_class",
            value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
        )
    }
)
private UUID userId;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda