我试图在两个实体之间创建一对一的关系:
>
项目实体
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne(mappedBy = "project", cascade = CascadeType.ALL, optional = false, fetch = FetchType.LAZY)
private CrawlerConfiguration crawlerConfiguration;
// Getters and setters ...
public void setCrawlerConfiguration(CrawlerConfiguration crawlerConfiguration) {
if (crawlerConfiguration == null) {
if (this.crawlerConfiguration != null) {
this.crawlerConfiguration.setProject(null);
}
} else {
crawlerConfiguration.setProject(this);
}
this.crawlerConfiguration = crawlerConfiguration;
}
爬网程序配置实体
@Entity
@Table(name = "crawler_configurations")
public class CrawlerConfiguration {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Project project;
// Getters and setters ...
}
当用户创建一个新项目时,也应该为该项目创建一个配置。
@Transactional
public Project createProject(Project project) {
project.setCrawlerConfiguration(new CrawlerConfiguration());
return projectRepository.save(project);
}
不幸的是,这会导致以下异常:
javax.persistence.EntityExist异常:具有相同标识符值的不同对象已经与会话关联:[com.github.peterbencze.serritorcloud.model.entity.CrawlerCon人和#1]
创建实体的正确方法是什么?
试试这个
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Project project;
在CrawlerConfiguration实体中