我正在尝试在2个实体之间创建一对一关系:


项目实体

@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;
    }

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.EntityExistsException:与对象不同的对象
相同的标识符值已与会话相关联:
[com.github.peterbencze.serritorcloud.model.entity.CrawlerConfiguration#1]


创建实体的正确方法是什么?

最佳答案

试试这个

 @OneToOne(fetch = FetchType.LAZY)
 @PrimaryKeyJoinColumn
 private Project project;


在您的CrawlerConfiguration实体中

10-04 18:59