I have a persistent entity that has a @OneToMany
list of another entity and I need the list order to be able to be edited by the user, which works wonderfully. I can completely re-order the java List in memory and when I save() the object the order of links in the linking table does change. However, it changes to the reverse order of what the user set. However, if you pull the entity back up before closing the program, it shows up correct, because it's not reloading. If you reload the program, again, it's backwards.
Is this just not something I'm supposed to do, depend on that order? But making another order column seems redundant since there is an order anyway, and I can seem to change it. I just need it to save not backwards.
Any ideas?
Hibernate has support of ordered elements using IndexColumn annotation.
Here is an example from "Java Persistence with Hibernate" book :
@org.hibernate.annotations.CollectionOfElements
@JoinTable(
name = "ITEM_IMAGE",
joinColumns = @JoinColumn(name = "ITEM_ID")
)
@org.hibernate.annotations.IndexColumn(
name="POSITION", base = 1
)
@Column(name = "FILENAME")
private List<String> images = new ArrayList<String>();
I ran into the same issue, and I fixed it simply by adding @OrderBy annotation as suggested in another article here. I think it should be able to solve your problem as well, here is my code:
@Entity
@Table(name = "my_library")
public class MyLibrary implements java.io.Serializable{
(...omitted)
private List<Book> bookList = new ArrayList<Book>();
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL)
@OrderBy
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList= bookList;
}
}
Then I'm able to getBookList() as the same order I inserted while persisting to DB. When we don't specify the column name like @OrderBy("xxxColumn") , it uses the primary key of that entity by default. In my case, it uses instanceId of Book, which will always follow the same order as insert order, so it serve my need well.
However, I'm curious about why the order was reverse in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With