Hi. Im new with Hibernate and im trying to implement some small projects. Im having trouble mapping something and after 2 days trying to solve it by myself i decided to ask for help. I will simplify the example to the main problem and i will avoid the entities details.
I have 2 classes:
Products (Long id)
Orders (Long id, Collection order_product)
Each order has a collection of products and the ammount of products of that kind ordered (Example : Order = {3 books, 2 cars, 1 ship})
Since its an N:N relationship, i get a intermediate table
Orders_Products that contains the 2 foreign keys and
another aditional field with the ammount of products ordered:
Orders_Products (Long Order_Id,Long Product_Id, int ammount)
I used the recommended intermediate class for mapping the composite keys at Orders_Products table so now i have 3 entities.
Code:
@Entity
@Table(name = "Products")
public class Product {
@Id
@GeneratedValue
@Column(name = "product_id")
}
Code:
@Entity
@Table(name = "Order_Products")
public class Order_Products {
@Embeddable
public static class Composite_Id implements Serializable {
@Column(name="order_fk")
private Long order;
@Column(name="product_fk")
private Long product;
public Composite_Id() {
}
public Composite_Id(Long order_id, Long product_id) {
this.order = order_id;
this.product = product_id;
}
}
@EmbeddedId
private Composite_Id id = new Composite_Id();
@ManyToOne
@JoinColumn(name = "order_fk", insertable = false, updatable = false)
private Order order;
@ManyToOne
@JoinColumn(name = "product_fk", insertable = false, updatable = false)
private Product product;
@Column(name = "ammount")
private Integer ammount;
//Getters and setters
}
Those 2 entities are correctly mapped i think. The tables are correctly created and everything works fine. Im having problems with the collectiong mapping. I want to be able to add to an Order entitiy, a Product and the ammount, and get the Order_Products entity and added to the list. This is what i have atm.
Code:
@Entity
@Table(name = "Orders")
public class Order {
@Id
@GeneratedValue
@Column(name = "order_id")
private Long id;
@CollectionOfElements
//I deleted other annotations i had here
private Collection<Orders_Products> orderProduct = new ArrayList<Orders_Products>();
//getters and setters
public void addElement(Product product,Integer ammount){
//......
}
}
I activated the show sql on my hibernate configuration and when i insert something into the Collection i get something like:
insert into Orders_Products(Orders_order_id, orderProduct_order_fk, orderProduct_producto_fk)... and cant get it mapped correctly.
Any advice is wellcome.
Thx in advance for your answers.