Search code examples
javajpaeclipselink

Jpa Persist primary key restriction violation


I'm having some problem on transitive persistence. Now I try to describe my problem in a more detailed way. I have two entities Row and Field.

    @Entity
public class Row implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="ROW_IMPORT_ID_GENERATOR", sequenceName="SEQ_RIGA_IMPORT")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ROW_IMPORT_ID_GENERATOR")
    private Long id;

    //bi-directional many-to-one association to CampoImport
    @OneToMany(mappedBy="row", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Field> fields;

    //Getters and setters method

    public void addField(Field fieldToAdd){

        if(fields==null)
            fields = new ArrayList<Fields>();

        fields.add(campoToAdd);
        fieldToAdd.setRow(this);

    }
}


@Entity
public class Field implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name="FIELD_IMPORT_ID_GENERATOR", sequenceName="SEQ_CAMPO_IMPORT")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="FIELD_IMPORT_ID_GENERATOR")
    private Long id;

    private String description;

    //bi-directional many-to-one association to RigaImport
    @ManyToOne
    @JoinColumn(name="ID_ROW")
    private Row row;

    //Getters and setters method
}

This is the sql statement to make the sequences:

CREATE SEQUENCE SEQ_RIGA_IMPORT INCREMENT BY 1 START WITH 1 MAXVALUE 999999999999999999 MINVALUE 1;

CREATE SEQUENCE SEQ_CAMPO_IMPORT INCREMENT BY 1 START WITH 1 MAXVALUE 999999999999999999 MINVALUE 1;

Now when i try to run the following snippet of code:

Row rowToSave = new Row(some parameters);
Field fieldToSave = new Field( some parameters);
rowToSave.addField(fieldToSave);
rowRepository.save(rowToSave);

I get this error:

Internal Exception: java.sql.SQLException: ORA-00001: violated    restriction of uniqueness (BILL.FIELD_PK)

Error Code: 1
Call: INSERT INTO FIELD (ID, DESCRIPTION, ID_ROW) VALUES (?, ?, ?)
bind => [3 parameters bound]

Where am I doing wrong?


Solution

  • Your database sequence object has an allocation size of 1, while JPA defaults to 50 which will cause this issue. Set your allocation size to match. see https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Ids/SequenceGenerator