我正在将JPA与Spring Boot结合使用(如果重要)并创建了两个表FileSystem和Media。两者都通过InheritanceType.JOINED关系连接(请参阅ER图)。此外,Filesystem是一个自引用表,它存储文件/文件夹的“树”及其子项和父项。
代码如下:
FileSystem.java
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class FileSystem {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column
private long id;
private String name;
public enum Type { FOLDER, FILE}
@ManyToOne
@JoinColumn(name="parent")
@JsonBackReference
private FileSystem parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL,orphanRemoval = true)
@JsonManagedReference
List<FileSystem> childs = new ArrayList<FileSystem>();
FileSystem.Type type;
}
Media.java
@Entity
public class Media extends FileSystem implements FieldHandled{
@JsonIgnore
private FieldHandler fieldHandler;
@JsonIgnore
@Lob
@Column( length = 100000 )
@Basic(fetch = FetchType.LAZY, optional = false)
private byte[] data;
}
MediaRepository.java
public interface MediaRepository extends JpaRepository<Media, Long>{
Media save(Media pageTemplate);
Media findOne(Long id);
public List<Media> findAllByParentId(Long parent);
public List<Media> findAllByParentIsNull();
public List<Media> findByName(String name);
}
在我的控制器方法中删除
...
MediaRepository mediaRepository;
mediaRepository.delete(mediaToDelete);
...
添加新媒体,获取它们等等到目前为止工作正常。但是,当我使用我的扩展delete()
为FileSystem
调用具有多个子(和子项)的JpaRepository
时,我得到以下异常:
无法删除或更新父行:外键约束失败(
repo
。file_system
,CONSTRAINTFKf57w77uiwcpfmbtl9lpuq9j9m
FOREIGN KEY(parent
)参考file_system
(id
))
最奇怪的是日志。似乎在第一步中JPA正在删除媒体行(由于InheritanceType是JOINED,IMO是正确的),然后尝试删除文件系统行(IMO不正确,因为它应该首先以递归方式删除它的所有子节点):
2016-10-19 16:21:43.530 TRACE 11412 --- [nio-8080-exec-1] org.hibernate.type.EnumType : Returning [FOLDER] as column [type3_6_0_]
2016-10-19 16:21:43.530 DEBUG 11412 --- [nio-8080-exec-1] org.hibernate.SQL : delete from media where id=?
Hibernate: delete from media where id=?
2016-10-19 16:21:43.531 TRACE 11412 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [65]
2016-10-19 16:21:43.533 DEBUG 11412 --- [nio-8080-exec-1] org.hibernate.SQL : delete from file_system where id=?
Hibernate: delete from file_system where id=?
2016-10-19 16:21:43.534 TRACE 11412 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [65]
2016-10-19 16:21:43.535 WARN 11412 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1451, SQLState: 23000
2016-10-19 16:21:43.535 ERROR 11412 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Cannot delete or update a parent row: a foreign key constraint fails