我使用Spring Boot 1.3.1.RELEASE与Hibernate和H2进行集成测试。以下是我对单向OneToMany关系的兴趣。由于某种原因,生成的外键DDL不包含ON DELETE CASCADE。根据{{3}},支持参考动作。我尝试了双向OneToMany,但仍然缺少ON DELETE CASCADE。请指教。如果可能的话,我想避免使用Hibernate特定的东西。提前谢谢。
我的实体:
@MappedSuperclass
public abstract class DomainObjectLong implements Persistable<Long> {
@Id
@GenericGenerator(name="ID_GEN" , strategy="increment")
@GeneratedValue(generator = "ID_GEN")
private Long id;
@Override
@Transient
public boolean isNew() {
return id == null;
}
}
@Entity
@Table(name = "event")
public class EventVO extends DomainObjectLong {
@Column(name = "time", nullable = false, updatable = false)
private LocalDateTime time = LocalDateTime.now();
@Column(name = "type", nullable = false, updatable = false)
@Enumerated(STRING)
private EventType type;
@OneToMany(cascade = ALL, fetch = EAGER, orphanRemoval = true)
@JoinColumn(name = "event_id", nullable = false)
private List<EventDataVO> data;
}
@Entity
@Table(name = "event_data", uniqueConstraints = {
@UniqueConstraint(columnNames = {"event_id", "key"})
})
public class EventDataVO extends DomainObjectLong {
@Column(name = "key", length = 128, nullable = false, updatable = false)
private String key;
@Column(name = "value", length = 512, nullable = false, updatable = false)
private String value;
}
属性:
datasource.runtime.url=jdbc:h2:mem:runtimetestdb;DB_CLOSE_ON_EXIT=FALSE
datasource.runtime.driver-class-name=org.h2.Driver
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=create-drop
日志:
23:40:44.648 [localhost-startStop-1] DEBUG org.hibernate.SQL -
alter table event_data
add constraint FK_6xxhltyiilvlk02730x7mu7cu
foreign key (event_id)
references event
Hibernate:
alter table event_data
add constraint FK_6xxhltyiilvlk02730x7mu7cu
foreign key (event_id)
references event
答案 0 :(得分:1)
JPA不会生成ON DELETE CASCADE约束。
原因是在JPA级别上使用toMany或toOne映射映射中的cascade属性完成了级联。
如果数据库将级联删除,则状态将与持久性上下文不匹配,并且JPA将生成删除但数据库记录已被删除。