Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jpa - @OrderColumn annotation in Hibernate 3.5

I'm trying to use the @OrderColumn annotation with Hibernate 3.5

@OneToMany(mappedBy = "parent",fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@OrderColumn(name = "pos")
private List<Children> childrenCollection;

When retrieving data, everything works fine. But I can't make it reorder elements in the List and save the new order to the database.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The combination of @OneToMany(mappedBy="...") and @OrderColumn is not supported by Hibernate. This JIRA issue tracks a request to throw a more obvious error message when this invalid combination is used: http://opensource.atlassian.com/projects/hibernate/browse/HHH-5390

I think that this isn't supported mainly because it is an odd relational pattern. The annotations above indicate that the "one" side of the relationship determines how the relationship will be flushed to the database, but the order/position is only available on the "many" side by examining the List. It makes more sense for the "many" side to own the relationship, since that side knows about both the membership and the ordering of the elements.

The Hibernate Annotations docs describe this situation in some detail:

http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection-extratype-indexbidir

The workaround is to remove the "mappedBy" attribute, which will cause the association to use the default join table strategy instead of a column on the target table. You can specify the name of the join table using the @JoinTable annotation.

The net effect of this change is that the "many" side of the relationship now determines how the relationship is persisted. Your java code needs to ensure that the List is updated properly, because Hibernate will now disregard the "one" side when flushing the entities.

If you still want to have the "one" side accessible in Java, map it with

@ManyToOne
@JoinColumn(name="...", insertable=false, updatable=false, nullable=false)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...