无法使用hibernate / jpa将UUID存储到MySql数据库中

时间:2017-07-19 23:26:08

标签: hibernate jpa spring-data uuid

我有一个包含此列的数据库表:

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接口,它弹出数据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的内容?

提前致谢:)

1 个答案:

答案 0 :(得分: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