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
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
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