How do I describe a bridge table to Ebean?

霸气de小男生 提交于 2019-12-06 22:40:19

问题


Lets say I have these tables:

ORDER: id
ITEM: id
ORDER_ITEM: order_id, item_id

The table: ORDER_ITEM is a bridge table between ORDER and ITEM.

How do I describe this threesome to Ebean?

I would prefer not to use raw SQL so that I can still create and update these entities.

UPDATE Sat Nov 9 02:32:40 UTC 2013

Ok, lets make this problem harder and more representative of my actual situation. The column names dont fit the convention:

ORDER: order_number
ITEM: item_number
ORDER_ITEM: my_order, my_item

回答1:


You don't have to create special bridge table yourself unless you want to have other fields there except foreign keys.

In Order class you should define field:

@ManyToMany
public List<Item> items;

In Item class:

@ManyToMany(mappedBy = "items")
public List<Order> orders;

And Ebean will generate bridge table for you.

And moreover:

You can have asymmetric relationship types between two classes:

@ManyToMany
@JoinTable(name="Order_Item")
public List<Item> items;

and

@ManyToOne
public Order order;

in case when order is an optional field in Item and you don't want to have a lot of empty fields in Item table.

UPDATE:

This will work for you. All the table and column names are now explicitly named by annotations:

@Entity
@Table(name="ITEM")
public class Item extends Model {
    @Id
    @Column(name="item_number")
    public Integer id;

    @ManyToMany(mappedBy = "items")
    public List<Order> orders;
}

and

@Entity @Table(name="ORDER") public class Order extends Model {
    @Id
    @Column(name="order_number")
    public Integer id;

    @ManyToMany
    @JoinTable(name="ORDER_ITEM",
            joinColumns=@JoinColumn(name="my_order",referencedColumnName = "order_number"),
            inverseJoinColumns = @JoinColumn(name="my_item", referencedColumnName="item_number"))
    public List<Item> items; }

The code is here: https://github.com/cosmolev/BridgeTable/tree/master/app/models



来源:https://stackoverflow.com/questions/19850491/how-do-i-describe-a-bridge-table-to-ebean

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