使用@OneToMany关系更新实体

时间:2020-09-11 16:07:52

标签: hibernate jpa spring-data-jpa

我将类AEntity定义为与ManyToOne双向的关系BEntity

BEntity类中,我与ManyToOneCEntity的关系。

@Entity
public class AEntity {

    @Id
    private String aId;

    @ManyToOne
    @JoinColumn(name = "b_id", updatable = false)
    private BEntity bEntity;
    
}


@Entity
public class BEntity {

    @Id
    private String bId;

    @OneToMany
    @JsonIgnore
    @JoinColumn(name = "b_id")
    private Set<AEntity> aEntites;
    
    @ManyToOne
    @JoinColumn(name = "cId", updatable = false)
    private CEntity cEntity;
    
}


@Entity
public class CEntity {

    @Id
    private String cId;
    
    @OneToMany(mappedBy = "cEntity", cascade = CascadeType.ALL)
    private Set<BEntity> bEntites;
    
}

我想更新BEntity以添加新数据aEntites,我尝试使用以下代码,但是出现此错误:

找不到ID为xxxx的AEntity;嵌套异常为 javax.persistence.EntityNotFoundException:无法找到具有以下内容的AEntity id xxxx

BEntity bEntity = getBEntity(event.agreementId);
            
Set<AEntity> aEntities = bEntity.getAEntites();
aEntities.add(new AEntity(event.aId, bEntity));
            
bEntity.setAEntites(aEntities);
bRepository.save(bEntity);

0 个答案:

没有答案