使用一对一关系时如何解决“具有相同标识符值的不同对象已与会话相关联”错误

问题描述 投票:0回答:1

我正在尝试在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]

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

java spring hibernate spring-boot hibernate-mapping
1个回答
0
投票

尝试一下

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

在您的CrawlerConfiguration实体中

© www.soinside.com 2019 - 2024. All rights reserved.