Hi everybody,
I have a database with two table "Item" and "Order" which are associated by a third table "Item_Order" which store some additionnal information :
Table Item : Id Integer
Table Order : Id Integer
Table Item_Order : item_id Integer, order_id Integer, status String
I am using hibernate 3.3.2 GA and Spring.
My Java Object are :
Code:
@Entity
public class Item {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.item", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@Cascade({org.hibernate.annotations.CascadeType.ALL,org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private List<ItemOrder> orders= new LinkedList<ItemOrder>();
// getter and setter
}
Code:
@Entity
public class Order {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.order", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@Cascade({org.hibernate.annotations.CascadeType.ALL,org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private List<ItemOrder> items = new LinkedList<ItemOrder>();
// getter and setter
}
Code:
@Entity
@Table(name = "item_order")
@AssociationOverrides( { @AssociationOverride(name = "pk.item", joinColumns = @JoinColumn(name = "item_id")),
@AssociationOverride(name = "pk.order", joinColumns = @JoinColumn(name = "order_id")) })
public class ItemOrder{
private ItemOrderPk pk = new ItemOrderPk();
@EmbeddedId
private ItemOrderPk getPk() {
return pk;
}
@Column (name = "status")
private String status;
@Transient
public Article getItem() { return getPk().getItem(); }
@Transient
public Commande getOrder() { return getPk().getOrder(); }
// setter, hashCode and equals
}
Code:
@Embeddable
public class ItemOrderPk implements Serializable {
private static final long serialVersionUID = -2700739856925530035L;
private Item item;
private Order order;
@ManyToOne
public Article getItem() { return item; }
@ManyToOne
public Commande getOrder() { return order; }
// setter, hashCode and equals
}
My test function is :
Code:
@Test
public void createOrder() {
Order order = new Order();
order.setFoo("bar");
Item item = new Item();
item.setBar("foo");
ItemOrder assoc = new ItemOrder();
assoc.setItem(item);
assoc.setOrder(order);
assoc.setStatus(foo.bar);
ArrayList<ItemOrder> assocs = new ArrayList<ItemOrder>();
assocs.add(assoc);
order.setItem(assocs);
// ItemManager.addItem(item);
OrderManager.addOrder(order);
}
OrderManager.addOrder will do :
Code:
hibernateTemplate.saveOrUpdate(order);
My problem is with this code, only order is inserting in the database.
If I uncomment ItemManager.addItem(item); item is inserting in the database.
But I have no solution to have the association information (in table Item_Order) inserted in the database.
What is wrong in my code ? What to do to have the assocation information inserted in the database ?
Thanks