【问题标题】:@ElementCollection in H2 not deleted (DataIntegrityViolationException)H2 中的 @ElementCollection 未删除 (DataIntegrityViolationException)
【发布时间】:2020-08-21 06:51:30
【问题描述】:

当我尝试从内部包含 @ElementCollection 的表中删除一个条目时,H2-Database 出现以下异常。使用 SQL-Server 一切正常。

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<>();

  ....

删除语句:

componentRepository.deleteById(componentId);

例外:

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

【问题讨论】:

    标签: spring-boot hibernate h2 junit5 spring-test


    【解决方案1】:

    这是一个一般的休眠问题https://hibernate.atlassian.net/browse/HHH-5529

    为了解决这个问题,在 ElementCollection 中添加了以下注释。

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

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 2011-04-14
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 2012-04-18
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多