【问题标题】:Failed to store UUID into MySql database using hibernate/jpa无法使用 hibernate/jpa 将 UUID 存储到 MySql 数据库中
【发布时间】:2017-12-25 10:32:23
【问题描述】:

我有一个包含此列的 db 表:

uuid CHARACTER(36) NOT NULL

它也是UNIQUE INDEX (uuid),但不是主键。

在Entity类中,uuid列的定义是这样的:

    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(name = "uuid", updatable = false, nullable = false)
    private UUID uuid;

然后有一个Repository接口,即spring data Repository接口:

@Repository
public interface SaveRepository extends Repository<CoreEvent, Integer> {
}

当我调用 saveRepository.save() 时,它抱怨 uuid 值为 null:

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)

... ...

Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'uuid' cannot be null

在将记录保存到数据库之前,为了生成 uuid,我是否遗漏了什么?

提前致谢:)

【问题讨论】:

    标签: hibernate jpa spring-data uuid


    【解决方案1】:

    你可以使用@PrePersist之类的事件来填充UUID字段https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

    但是为什么在创建对象时不分配 uuid uuid = UUID.randomUUID() ?

    重复? How to Generate an auto UUID using Hibernate on spring boot

    猜你喜欢
    • 2017-09-22
    • 2016-11-03
    • 2011-10-01
    • 2022-01-08
    • 1970-01-01
    • 2016-10-24
    • 2014-06-01
    • 2015-06-11
    • 2020-08-17
    相关资源
    最近更新 更多