Search code examples
spring-boothibernateh2junit5spring-test

@ElementCollection in H2 not deleted (DataIntegrityViolationException)


When i try to remove a entry from a table which has a @ElementCollection inside, i get following exception with the H2-Database. With a SQL-Server everything works fine.

application.yml

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:h2_test;MODE=MSSQLServer;INIT=CREATE SCHEMA IF NOT EXISTS test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password:
  liquibase:
    change-log: classpath:db/changelog.xml
    default-schema: test
    liquibase-schema: test
    enabled: false
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update

Component.class

@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table
@NoArgsConstructor
public class Component extends Identifiable {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "component_sequence")
  @SequenceGenerator(name = "component_sequence", sequenceName = "component_sequence", allocationSize = 10)
  private Long id;

  @Column
  private String componentId;

  @ElementCollection
  @CollectionTable(name = "parts", joinColumns = @JoinColumn(name = "component_id"))
  @Column(name = "part")
  private List<Integer> parts = new ArrayList<>();

  ....

Delete statement:

componentRepository.deleteById(componentId);

Exception:

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["FKTCOK4MNSV7BPTFXPGQWRDFKAR: TEST.PARTS FOREIGN KEY(COMPONENT_ID) REFERENCES TEST.COMPONENT(ID)

Solution

  • It is a general Hibernate Problem https://hibernate.atlassian.net/browse/HHH-5529.

    To solve this, I have added the following annotations to the ElementCollection.

    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "component_id")