首页 > 解决方案 > 同一实体的多个表示正在与@OneToMany 合并

问题描述

我有一个使用 Spring Boot 构建的 Web 应用程序,该应用程序与一个 db PostgreSql 连接,该项目是关于一个教育机构并管理学生和发票......

我手动生成所有发票。我通常添加第一个 cuota(发票),但是当我想生成第二个时,我遇到了这个问题:

java.lang.IllegalStateException: Multiple representations of the same entity [com.codeboros.app.entity.Cuota#1] are being merged. Detached: [com.codeboros.app.entity.Cuota@1788e1df]; Managed: [com.codeboros.app.entity.Cuota@2697e3fc]

我有这个实体:

@Entity
@Table(name="ALUMNOS")
public class Alumno implements Serializable {           
    @OneToMany(mappedBy="alumno", cascade= {CascadeType.DETACH,CascadeType.PERSIST,CascadeType.DETACH,CascadeType.REMOVE,CascadeType.REFRESH,CascadeType.MERGE}, fetch=FetchType.LAZY)
    @NotFound(action = NotFoundAction.IGNORE)
    @JsonIgnore 
    private List<Cuota> cuotas;
}

@Entity
@DiscriminatorValue(value="Cuota")
public class Cuota extends Factura implements Serializable  {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="alumno_cod")
    @NotFound(action = NotFoundAction.IGNORE) 
    Alumno alumno;
}

和 AlumnoController

@PostMapping("/alumnoGenCuota/{id}")    
public String GenCuota(@PathVariable Long id, Cuota cuota) {
    Alumno alumno = alumnoService.get(id);
    cuota.setAlumno(alumno);
    cuota.setMonto(alumno.getCurso().getCuota()); 
    cuota.setDetalle(alumno.getCurso().getNombre()+":  $"+alumno.getCurso().getCuota()); //detalle
    alumno.AgregarCuota(cuota);             

    alumnoService.save(alumno);

    return "redirect:/alumnocuotas/"+id;
}

我试图删除 CascadeType.MERGE 但不保存新闻 Cuotas

标签: postgresqlspring-bootjpa

解决方案


如果您没有使用 Hibernate,请CascadeType.MERGE从不允许您持久化分离的实体的实体中删除或放置除CascadeType.MERGE

如果您使用的是 Hibernate,请将以下几行添加到您的 persistence.xml -

<property name="hibernate.event.merge.entity_copy_observer" value="allow"/>

当您设置 时hibernate.event.merge.entity_copy_observer=allow,Hibernate 将在级联合并操作时合并检测到的每个实体副本。在合并每个实体副本的过程中,Hibernate 会将每个实体副本的合并操作级联到其与cascade=CascadeType.MERGEor的关联CascadeType.ALL。当另一个实体副本被合并时,合并一个实体副本产生的实体状态将被覆盖。


推荐阅读