Issue
I have @OneToMany
and @ManyToOne
relationship between parent and child entities.
@Entity
@Table(name = "parent")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@OneToMany(targetEntity=Measurement.class, mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
@JsonManagedReference
private List<Child> children = new ArrayList<>();
}
and I have child entity like this
@Entity
@Table(name = "child")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(targetEntity=Parent.class, fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonBackReference
private Parent parent;
After saving this data, the database looks like following,
Parent:
id
1
Child
id parent_id
2 1
my question is, why does the primary key of child is 2 and not 1? In the child table, it could have a primary key as 1 and foreign key reference to parent as 1. When I add one more parent, then the tables looks like this,
Parent:
id
1
3
Child
id parent_id
2 1
4 3
Am I doing something wrong or it is the expected behaviour?
Solution
The generation strategy @GeneratedValue(strategy = GenerationType.AUTO)
will takes value from the default hibernate sequence
, so the same sequence is used for all key generation.
When you are inserting the data, it inserts in the sequence like Parent then Child, as it is getting values from the same sequence generator, it will increase in sequence for all your table.
You need to use the GenerationType.IDENTITY
strategy for your purpose.
In parent Parent
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
In child
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
Answered By - SSK
Answer Checked By - Timothy Miller (JavaFixing Admin)