The issue here is that the RecommendationInstance entity is a separate and independent entity that does not have a mapping for the order column. Eclipselink is designed to create inserts only from the entity itself. There is a feature request to have eclipselink store statements and add to them as it processes other mappings, I still don't have it handy though.
Why does JPA update the OrderColumn instead of setting it on creation?
-
19-07-2023 - |
Question
I want to add a NOT NULL constraint to my table on my OrderColumn. Running my code with the constraint I get a constraint violation error. Running without the constraint I see that the row is first inserted without the OrderColumn, and then updated immediately after with the correct OrderColumn. Is there a reason for this behavior?
My entity managing the OrderColumn:
@Entity
@Table(name="INSPECTION")
public class Inspection implements Serializable
{
...
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, orphanRemoval=true)
@OrderColumn(name="LIST_INDEX", nullable=false)
@JoinColumn(name="INSPECTION_ID")
private List<RecommendationInstance> recommendations;
...
}
This question stemmed from Why is JPA ignoring my @OrderColumn in a basic use case? where I was confused as to why my OrderColumn wasn't getting inserted. Additional code samples can be seen there.
La solution
Autres conseils
In order to avoid this type of errors, try adding a default value to the field in your database table, e.g. for mysql:
alter table YourTable modify column index_column int(5) not null default 0;
That way, in case your JPA provider (e.g. eclipselink) first makes inserts without giving index_column a value, it'll give a default value of 0, avoiding this error. If the JPA provider then refreshes this value with the correct one, there should be no problem.