【发布时间】:2017-06-30 16:40:59
【问题描述】:
当删除孩子的父母(在一对多的单向关系中)时,我不断收到这些错误。 当我先删除孩子时,一切正常。
我不需要/想要双向关系。
这是父母:
@Entity
@Table(name = "datagroup")
public class DataGroup implements java.io.Serializable {
@Id
@Column(name = "group_id", unique = true, nullable = false)
private int group_id;
private String name;
@OneToMany( targetEntity=DataGroupItem.class, fetch=FetchType.LAZY, cascade = CascadeType.REMOVE)
@JoinColumn(name="group_id")
private List<DataGroupItem> dataGroupItems = new ArrayList<>( 0);
... setters and getters
}
这是孩子:
@Entity
@Table(name = "datagroupitems")
public class DataGroupItem implements java.io.Serializable {
@Id
@Column(name = "item_id", nullable = false)
private int item_id;
private String name;
@Column(name = "group_id", nullable = false)
private int group_id = 0; // only for (un)delete
... getters and setters
}
当我在控制器中删除父级时:
@RestController
@RequestMapping("/learner/groups")
public class LearnerSyncServices {
@Autowired
private IDataGroupRepository dataGroupRepository;
@Autowired
private IDataGroupItemRepository dataGroupItemRepository;
...
@RequestMapping( method= RequestMethod.DELETE, value="/{id}")
public void delete(@PathVariable String id) {
try {
int idx = Integer.parseInt( id);
dataGroupRepository.delete( idx);
} catch (Exception e) {
logger.error( "Cannot delete " + id + " " + e.getMessage());
}
}
作为 JPA 版本,我拥有:Spring Boot 版本 4.1.3。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
删除至少有 1 个孩子的组会显示以下消息:
.. WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1048, SQLState: 23000
.. ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Column 'group_id' cannot be null
.. INFO org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl - HHH000010: On release of batch it still contained JDBC statements
.. ERROR nl.deholtmans.tjm1706.learner.LearnerSyncServices - Cannot delete 101 could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
【问题讨论】:
-
组的引用是
nullable=false。您要么需要为每个孩子设置一个新的引用,要么使用级联删除每个孩子(如果需要的话)。 -
您能否详细说明“nullable=false”以及您的两个选项?也许最好将其放在答案中(而不是评论)。首选是级联删除:删除组及其所有的孩子
-
你试过CascadeType DELETE_ORPHAN吗?
-
哦,它已被废弃,现在它的 @OneToMany(orphanRemoval = true)
-
没有任何改变,仍然是一个错误。