Why does JPA update the OrderColumn instead of setting it on creation?

余生长醉 提交于 2019-12-11 11:03:02

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23567267/why-does-jpa-update-the-ordercolumn-instead-of-setting-it-on-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!