Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate OneToMany List ordering persisting but reversing?

Tags:

list

hibernate

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?

like image 586
Joshua Avatar asked May 21 '09 20:05

Joshua


2 Answers

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>();
like image 182
Pavel Rodionov Avatar answered Oct 23 '22 05:10

Pavel Rodionov


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.

like image 37
Paul Lo Avatar answered Oct 23 '22 06:10

Paul Lo