我有两个实体项目和用户。项目具有2个字段:所有者和创建者,它们是用户对象。 这些字段由@OneToOne(cascade = CascadeType.ALL)映射。
我可以与其他所有者和创建者一起保存项目。 当我尝试使用相同的所有者和创建者保存Project对象时,收到以下错误消息:
已经有一个具有相同标识符值的不同对象 与会话相关联
原因是Hibernate使用CascadeType.ALL保存。 当2个字段引用表中的同一对象/行时,是否可以使用Cascade保存此Project对象?
项目实体:
/api
}
用户实体:
server
ProjectRepository:
package com.entity;
import java.sql.Timestamp;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="project")
public class Project {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="project_id")
private int projectId;
@Column(name="number")
private int number;
@Column(name="name")
private String name;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="owner_id")
private User owner;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="creator_id")
private User creator;
@Column(name="description")
private String description;
@Column(name="start_time")
private Timestamp startTime;
@Column(name="end_time")
private Timestamp endTime;
public Project() {
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getStartTime() {
return startTime;
}
public void setStartTime(Timestamp startTime) {
this.startTime = startTime;
}
public Timestamp getEndTime() {
return endTime;
}
public void setEndTime(Timestamp endTime) {
this.endTime = endTime;
}