I\'m using Hibernate 3.3.1 and am following along in modelling this sample table structure, but I\'m having trouble creating a join table with extra attributes.
It\
The code below seems to generate tables as desired, I have tested it on MySQL (just the table creation, not CRUD):
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "orderDetailId.order")
private List orderItems;
//get set …..
}
@Entity
@Table(name="products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "orderDetailId.product")
private List orderItems;
//get set ……
}
@Entity
@Table(name = "order_detail")
public class OrderDetail {
@Id
private OrderDetailId orderDetailId;
private double price;
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdatedTime;
//get set ….
}
@Embeddable
public class OrderDetailId implements Serializable{
private Order order;
private Product product;
@ManyToOne(fetch=FetchType.LAZY)
@Access(AccessType.PROPERTY)
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
@ManyToOne(fetch=FetchType.LAZY)
@Access(AccessType.PROPERTY)
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
//hash code equals override
}
Hibernate DEBUG details as below
DEBUG: org.hibernate.tool.hbm2ddl.SchemaUpdate - create table order_detail (lastUpdatedTime datetime, price double precision not null, product_id bigint, order_id bigint, primary key (order_id, product_id)) ENGINE=InnoDB
DEBUG: org.hibernate.tool.hbm2ddl.SchemaUpdate - create table orders (id bigint not null auto_increment, primary key (id)) ENGINE=InnoDB
DEBUG: org.hibernate.tool.hbm2ddl.SchemaUpdate - create table products (id bigint not null auto_increment, primary key (id)) ENGINE=InnoDB
DEBUG: org.hibernate.tool.hbm2ddl.SchemaUpdate - alter table order_detail add index FK23AE5A622128CF91 (order_id), add constraint FK23AE5A622128CF91 foreign key (order_id) references orders (id)
DEBUG: org.hibernate.tool.hbm2ddl.SchemaUpdate - alter table order_detail add index FK23AE5A62EB201631 (product_id), add constraint FK23AE5A62EB201631 foreign key (product_id) references products (id)