0

I have a One-Many relationship set between two entities - A workoutSession (parent) and an Exercise(child), a workout having many exercises.

However, when I try to save the Workout session, I get the error:

ERROR: duplicate key value violates unique constraint "exercise_pkey" Detail: Key (id)=(21) already exists.

I do not understand why an exercise does not have a unique key generated here ?

@Entity
@Table(name="workout")
public class Workout {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String category;

    private String type;

    private Timestamp duration;

    private String notes;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "id")
    private List<Exercise> exercises;
}




@Entity
@Table(name="exercise")
public class Exercise {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

@Column(name="name")
private String exerciseName;
}

table create scripts:

CREATE TABLE WORKOUT(
   ID  serial PRIMARY KEY      NOT NULL,
   NAME     CHAR(50) NOT NULL,
   CATEGORY CHAR(50),
   TYPE CHAR(50),
   DURATION TIMESTAMP,
   NOTES CHAR(500)
);

CREATE TABLE exercise (
  id serial primary key not null,
  workout  integer references workout(id),
  name char(100) NOT NULL
);
JCC
  • 11
  • 5
  • Check the DB column type. https://stackoverflow.com/questions/40497768/jpa-and-postgresql-with-generationtype-identity – Alan Hay Jan 28 '19 at 17:08
  • Yes I am using ID and SERIAL now, and have tried SEQUENCE with a hibernate sequence also. Neither solution worked. – JCC Jan 28 '19 at 17:16
  • Are you experiencing this sometimes or for any data insertion. – Anuj Vishwakarma Jan 28 '19 at 17:31
  • this is the only case I have configured in the app so far, it happens always. If I make the exercise collection transient it will insert the workout data only, and with no errors. but i need the exercise insertions too. – JCC Jan 28 '19 at 17:50

0 Answers0