gpt4 book ai didi

java - 使用一对一关系时如何修复 "A different object with the same identifier value was already associated with the session"错误

转载 作者:行者123 更新时间:2023-12-01 23:18:25 27 4
gpt4 key购买 nike

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

  • 项目实体

    @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: A different object with the same identifier value was already associated with the session : [com.github.peterbencze.serritorcloud.model.entity.CrawlerConfiguration#1]

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

最佳答案

试试这个

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

在您的 CrawlerConfiguration 实体中

关于java - 使用一对一关系时如何修复 "A different object with the same identifier value was already associated with the session"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58340066/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com