簡體   English   中英

如何正確使用 UUID 作為 @Entity 的 @Id?

[英]How can I use an UUID as an @Id for my @Entity properly?

我想將來自 Spring Boot 的 User 實體存儲到 MySQL 數據庫中,並且我想使用UUID作為Id 但是當我遵循在線解決方案時,我只會得到The userId doesn't have a default value 我就是不知道出了什么問題。 這是代碼:

用戶實體:

@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表:

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

錯誤信息:

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

首先,我必須注意到

根據 JPA,只有以下類型應用作標識符屬性類型:

  • 任何 Java 原始類型
  • 任何原始包裝類型
  • java.lang.String
  • java.util.Date (TemporalType#DATE)
  • java.sql.日期
  • java.math.BigDecimal
  • java.math.BigInteger

用於此列表之外的標識符屬性的任何類型都不可移植

但是,Hibernate 支持UUID標識符值生成。 這是通過其org.hibernate.id.UUIDGenerator id 生成器支持的。

您可以使用默認策略,即根據 IETF RFC 4122 的版本 4(隨機)策略。

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

或者另一種策略是 RFC 4122 版本 1(基於時間)策略(使用 IP 地址而不是 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM