美好时光。
比如说,有两个数据库表:FOLDERS和FOLDER_TYPES。
CREATE TABLE FOLDERS (
ID VARCHAR2(50 BYTE) NOT NULL,
NAME VARCHAR2(4000 BYTE) NOT NULL,
DESCRIPTION VARCHAR2(4000 BYTE),
FOLDER_TYPE_ID VARCHAR2(50 BYTE) NOT NULL,
PARENT_FOLDER_ID VARCHAR2(50 BYTE)
)
CREATE TABLE FOLDER_TYPES (
ID VARCHAR2(50 BYTE) NOT NULL,
NAME VARCHAR2(50 BYTE) NOT NULL,
DESCRIPTION VARCHAR2(4000 CHAR)
)
如您所见, FOLDER表中的 FOLDER_TYPE_ID 列上有一个NOT NULL约束。
这些表的 Hibernate 实体如下:
@Entity
@Table(name = "folders")
public class Folder implements Serializable {
private static final long serialVersionUID = 1856858081142422000L;
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "[ID]")
private String id;
@Column(name = "[NAME]")
private String name;
@Column(name = "[DESCRIPTION]")
private String description;
@ManyToOne
@JoinColumn(name = "folder_type_id")
private FolderType type;
...
和
@Entity
@Table(name = "folder_types")
public class FolderType implements Serializable{
private static final long serialVersionUID = -7992732910184226857L;
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "[ID]")
private String id;
@Column(name = "[NAME]")
private String name;
@Column(name = "[DESCRIPTION]")
private String description;
问题是:当我删除一个 Folder 对象时,在从 DB 中实际删除之前,Hibernate 尝试为引用(文件夹类型)设置一个空值,但存在约束,因此引发了异常。作为一种解决方法,我可以删除约束,但是如果需要它并且我不能更改表(FOLDERS)怎么办?
有没有办法说 Hibernate 不将实体更新为空引用?我尝试在文件夹实体中设置updatable = false
为@JoinColumn
(FolderType 类型),但没有运气......