Java 使用一对一关系时,如何修复“具有相同标识符值的不同对象已与会话关联”错误
我试图在两个实体之间创建一对一的关系: 项目实体Java 使用一对一关系时,如何修复“具有相同标识符值的不同对象已与会话关联”错误,java,spring,hibernate,spring-boot,hibernate-mapping,Java,Spring,Hibernate,Spring Boot,Hibernate Mapping,我试图在两个实体之间创建一对一的关系: 项目实体 @Entity @Table(name = "projects") public class Project { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(mappedBy = "project", cascade = CascadeType.ALL, optional = false,
@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.EntityExistsException:具有
相同的标识符值已与会话关联:
[com.github.peterbencze.serritorcloud.model.entity.crawlerConfiguration 1]
创建实体的正确方法是什么?试试这个
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private Project project;
在您的爬网配置实体中感谢您的帮助。我尝试添加PrimaryKeyJoinColumn注释,结果出现了另一个异常:org.hibernate.id.IdentifierGenerationException:调用save之前必须手动分配此类的id:com.github.peterbencze.serritorcloud.model.entity.crawlerConfiguration抱歉,没有找到。您的爬虫配置表是否有Id列?您还应该在CrawlerConfiguration实体的Id上添加@GeneratedValuestrategy=GenerationType.IDENTITY,还可以添加@Columnname=Id、unique=true、nullable=False在添加这两个注释后,它不再引发异常。但是,它会在数据库中为配置生成2行。请从爬虫_配置中选择*;ID 1 2
@Entity
@Table(name = "crawler_configurations")
public class CrawlerConfiguration {
@Id
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Project project;
// Getters and setters ...
}