在Spring JPA Hibernate中未自动生成UUID

ztmd8pv5  于 2022-12-13  发布在  Spring
关注(0)|答案(1)|浏览(228)

这是我的模型定义:

@Entity
@Table(name = "decileconfig")
public class DecileConfig extends BaseEntity {

    @Id
    //@GeneratedValue(generator = "UUID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    @Type(type="org.hibernate.type.UUIDCharType")
    @NotNull(groups = DecileConfig.Existing.class)
    @Null(groups = DecileConfig.New.class)
    @Column(name="id", columnDefinition = "VARCHAR(255)", nullable = false)
    private String id; // This has to be String
..

这是我的表:

create table Allocationtest.global_configuration
  (
      id varchar(255) NOT NULL PRIMARY key,

当我尝试插入数据时,我得到以下信息:

**org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement**

我认为ID列的自动生成不发生。
更新:更改为以下内容后:

@GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Type(type="org.hibernate.type.UUIDCharType")
    @NotNull(groups = DecileConfig.Existing.class)
    @Null(groups = DecileConfig.New.class)
    @Column(name="id", columnDefinition = "VARCHAR(255)", nullable = false)
    private String id;

我得到这个:
org.springframework.web.util.NestedServletException:请求处理失败;嵌套的异常是一个系统异常:无法通过反射设置字段值[2b 221537 -1089- 4ab 3-ae 81-c8 fbf 44 bb 293]的值:配置com.walmart.sams.services.allocation.configuration.service.model.DecileConfig.id设置者;嵌套的异常是组织的休眠。无法通过反射设置字段值[2b 221537 -1089- 4ab 3-ae 81-c8 fbf 44 bb 293]的值:[类别com.walmart.sams.services.allocation.configuration.service.model.DecileConfig.id]的设定者,设定者的名称为com.walmart.sams.services.allocation.configuration.service.model.DecileConfig.id

ymdaylpp

ymdaylpp1#

只需将UUID指定为默认值:

@Entity
@Table(name = "decileconfig")
public class DecileConfig extends BaseEntity {

    @Id
    @NotNull(groups = DecileConfig.Existing.class)
    @Null(groups = DecileConfig.New.class)
    @Column(name="id", columnDefinition = "VARCHAR(255)", nullable = false)
    private String id = UUID.randomUUID().toString();

相关问题