'Problems with id when saving data using Spring Data JPA Kotlin

So when im trying to save data on a in memory H2 database with unit tests i get this following error. Saving works fine on normal postgres database. But im trying to make it work with H2 for unit tests.

> could not execute statement; SQL [n/a]; constraint [null]; nested
> exception is org.hibernate.exception.ConstraintViolationException:
> could not execute statement

This it the data class

@Entity
@Table(name = "delivery_type")
data class DeliveryType (
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    val id: Long = 0,
    @Column(name = "type")
    val type: String,
)

Im trying to run a simple test

@SpringBootTest
@Transactional
internal class CarQueueServiceTest {
    @Autowired
    lateinit var deliveryTypeRepo: DeliveryTypeRepo

    @Test
    fun addDeliveryType() {
        val deliveryType = DeliveryType(type = "Truck")
        println(deliveryTypeRepo.save(deliveryType))
    }
}

I will add some of the hibernate logs

Hibernate: create table delivery_type (id bigint generated by default as identity, type varchar(255), primary key (id))
    
Hibernate: insert into delivery_type (id, type) values (null, ?)
2022-03-21 11:36:00.656 TRACE 17340 --- [    Test worker] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Truck]
2022-03-21 11:36:00.660  WARN 17340 --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23502, SQLState: 23502
2022-03-21 11:36:00.660 ERROR 17340 --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : NULL not allowed for column "ID"; SQL statement:
insert into delivery_type (id, type) values (null, ?) [23502-210]

H2 setup

spring.h2.console.enabled=true
spring.h2.console.path=/h2_console
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto = create
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source