Quiero almacenar una entidad de usuario de Spring Boot en una base de datos MySQL y quiero usar un UUID como Id . Pero cuando sigo las soluciones en línea, solo obtengo The userId doesn't have a default value . Y simplemente no puedo entender qué está mal. Aquí está el código:
Entidad usuaria:
@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; }tabla mysql:
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 );El mensaje de error:
SQL Error: 1364, SQLState: HY000 2020-07-23 15:31:29.234 ERROR 16336 --- [nio-8080-exec-1] ohengine.jdbc.spi.SqlExceptionHelper : Field 'userId' doesn't have a default value 2020-07-23 15:31:29.251 ERROR 16336 --- [nio-8080-exec-1] oaccC[.[.[/].[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 causeAntes que nada tengo que notar que:
De acuerdo con JPA, solo los siguientes tipos deben usarse como tipos de atributo de identificador:
- cualquier tipo primitivo de Java
- cualquier tipo de contenedor primitivo
- java.lang.String
- java.util.Date (Tipo Temporal#FECHA)
- java.sql.Fecha
- java.math.BigDecimal
- java.math.BigInteger
Cualquier tipo usado para atributos de identificador más allá de esta lista no será transferible .
Pero, Hibernate admite la generación de valor de identificador UUID . Esto se admite a través de su generador de identificación org.hibernate.id.UUIDGenerator .
Puede utilizar la estrategia predeterminada, que es una estrategia de la versión 4 (aleatoria) según IETF RFC 4122.
@Id @Column(name = "userId", columnDefinition = "BINARY(16)") @GeneratedValue private UUID userId;O una estrategia alternativa que es una estrategia RFC 4122 versión 1 (basada en el tiempo) (usando la dirección IP en lugar de la dirección mac).
@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;