开发者

Manipulating join table row ordering using Hibernate annotations

I've done something similar to this with hbm files but so far I haven't found an equivalent using annotations. What I'd like to be able to do is create an as开发者_如何转开发sociation across a join table where the join table contains an order column for the association (sorry for any incorrect terminology here). At the very simplest, the tables might look like this:

Table: Menus
-----
menu_id

Table: Items
-----
item_id

Table: Menus_Items
----
menu_id
item_id
order_by

If I didn't require that menu items be ordered (this the order_by column) I could do this with no problem; however, I'd like to be able to programmatically order items in the Menus_Items table either in unit tests or in an admin tool. So for that, I think, I'll also need a MenuItems class, correct?

My question is, what annotations are needed on the corresponding classes to make this happen? The classes might look something like this (this is as far as I've got):

public class Menu {
    private List<MenuItem> items;

    // ...

    @OneToMany
    @JoinTable(name = "Menus_Items", 
        joinColumns = @JoinColumn(name = "menu_id"), 
        inverseJoinColumns = @JoinColumn(name = "item_id"))
    @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    @IndexColumn(name = "order_by")
    public List<MenuItem> getItems() { // ...
    }

}   // end class Menu

Is @IndexColumn correct? Programmatically, how do I specify the order of the MenuItems collection? What might I be doing wrong? I have a nagging feeling that I'm missing something obvious.

Any help much appreciated.


however, I'd like to be able to programmatically order items in the Menus_Items table either in unit tests or in an admin tool. So for that, I think, I'll also need a MenuItems class, correct?

If this is a real many-to-many, then what you have is correct. But you don't need an entity for the join table (more on this later).

My question is, what annotations are needed on the corresponding classes to make this happen? The classes might look something like this (this is as far as I've got)

As I said, you don't need this MenuItem entity for the join table and I'd expect to see a ManyToMany between Menu and Item instead (section 2.2.5.3.4. Indexed collections (List, Map) in the reference documentation).

Is @IndexColumn correct? Programmatically, how do I specify the order of the MenuItems collection?

The Hibernate specific @IndexColumn is correct. But if you are using a JPA 2.0 implementation, you should prefer the standard @OrderColumn annotation (example here).

Regarding the order, you are using an ordered collection (List) and the order is derived from the order of the elements in the List (more precisely, their index will be stored in the database). So just order the Item as you like in the List<Item>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜