1

I have a db table with this column:

uuid CHARACTER(36) NOT NULL

It's also a UNIQUE INDEX (uuid) but NOT a primary key.

In the Entity class, the definition of the uuid column is like this:

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

Then there is a Repository interface that spring data Repository interface:

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

When I called saveRepository.save(), it complains that the uuid value is 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

Did I miss anything in order to generate the uuid before saving the record to the db?

Thanks in advance :)

Evan_HZY
  • 984
  • 5
  • 17
  • 34

1 Answers1

1

u could use some events like @PrePersist to populate UUID field https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

but why just not assign uuid when object is created uuid = UUID.randomUUID() ?

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

Bartun
  • 549
  • 2
  • 12