我的应用程序具有一个带有此属性和JPA批注的实体类(Ativo):

@JoinColumn(name = "BOLSA", referencedColumnName = "ID")
@ManyToOne(optional = false, cascade = {CascadeType.PERSIST})
private Bolsa bolsa;


当我尝试保留实体类(Ativo)时,抛出此异常:

内部异常:java.sql.SQLIntegrityConstraintViolationException:该语句被中止,因为它会导致在“ BOLSA”上定义的“ SQL131102225757700”标识的唯一或主键约束或唯一索引中重复键值。

我不明白我的代码有什么问题。如果这只是现有对象的外键,为什么要尝试创建Bolsa类型的新对象?



Ativo类的负责人:

@Entity
@Table(name = "ATIVO")
public class Ativo implements EntityInterface<Ativo>, Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Long id;

    @Basic(optional = false)
    @Column(name = "CODIGO", unique=true, nullable = false)
    private String codigo;

    @Basic(optional = false)
    @Column(name = "TIPO_MERCADO", nullable = false)
    private String tipoMercado;

    @Column(name = "DESCRICAO", nullable = false, length = 10000)
    private String descricao;

    @JoinColumn(name = "BOLSA", referencedColumnName = "ID")
    @ManyToOne(optional = false, cascade = {CascadeType.PERSIST})
    private Bolsa bolsa;




Bolsa类的标题:

@Entity
@Table(name = "BOLSA")
public class Bolsa implements EntityInterface<Bolsa>, Serializable, Comparable<Bolsa> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Long id;

    @Basic(optional = false)
    @Column(name = "NOME", unique = true, nullable = false)
    private String nome;

    @Column(name = "DESCRICAO", nullable=false, length = 10000)
    private String descricao;

最佳答案

根据评论中的建议,从以下关系中删除cascade = {CascadeType.PERSIST}即可。

@JoinColumn(name = "BOLSA", referencedColumnName = "ID")
@ManyToOne(optional = false, cascade = {CascadeType.PERSIST})
private Bolsa bolsa;


原因是,Cascade Persist会通过传递持久性为您将事务放入数据库,因此您不必显式持久化父级(在您的情况下为“ Bolsa”)。但是,在持久化之前维护对象的内存状态始终是您的责任。

我怀疑(因为从提供的片段中看不出来)您在保存Bolsa之前显式地持久化了Ativo对象,因此可以通过删除级联持久性约束来解决该异常。

09-28 04:37