在使用JoinColum而不是mapledBy时,从@ManyToOne端驱动级联时,我无法使级联正常工作。
我将JpaRepository用于要保存的实体,并在其上调用save。该实体包含与普通用户表的@ManyToOne关系,该用户表可以具有其他也具有外键关系的实体。因此,联接是由JoinCoumn完成的。如果仅将MERGE指定为CascadeType,那么如果用户表中不存在该用户,则保存错误。如果我分配了{PERSIST,MERGE}或ALL,则用户将被保存到父用户表(如果该表不存在),但是如果存在,则会因主键冲突而出错(即仍尝试在主表上进行插入)父表)。
相关表格如下:
CREATE TABLE user (
user_id varchar(64) NOT NULL,
first_name varchar(64) NULL,
last_name varchar(64) NULL,
email varchar(128) NULL,
PRIMARY KEY
(
user_id
)
);
CREATE TABLE work_flow_data_archive (
workflow_entry_id int IDENTITY(1,1) NOT NULL,
user_id varchar (64) NULL,
state varchar(64) NULL,
workflow_id varchar(32) NULL,
PRIMARY KEY
(
workflow_entry_id
)
);
ALTER TABLE work_flow_data_archive WITH CHECK ADD CONSTRAINT
FK_user_workflow FOREIGN KEY(user_id)
REFERENCES user (user_id);
实体是:
@Entity
@NoArgsConstructor
public class WorkFlowDataArchive {
@Id
@GeneratedValue
@Column(name = "workflow_entry_id")
private int workflowEntryId;
private String workflowId;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private UserModel owningUser;
private String state;
...
}
@Entity(name="User") data class UserModel (
@Id
@Column(name = "user_id")
var userId: String? = null,
var firstName: String? = null,
var lastName: String? = null,
var email: String? = null
)
我宁愿避免将关系的OneToMany放在UserTable上,例如
@OneToMany
var workflowDataArchive: Set<WorkFlowDataArchive>? = null
因为还会有其他实体引用用户。我缺少使合并在此设置中不起作用的东西吗?