Monday, September 16, 2013

Hibernate one-to-many with child entity using composite primary key

Scenario: A customer can have multiple orders. The customer entity has cid as primary key, the order has composite primary key (order_id + cid)

Database tables:

 CREATE TABLE customers (
    cid VARCHAR(8) PRIMARY KEY,
    name VARCHAR(255)
 );

 CREATE TABLE orders (
    order_id INT,
    customer_id VARCHAR(8),
    amount REAL,
    PRIMARY KEY(order_id, customer_id),
    FOREIGN KEY(customer_id) REFERENCES customers(cid)
 );

The Java code using Hibernate ORM will be

Customer.java

@Entity
@Table(name="customers")
public class Customer implements Serializable {
    @Id
    @Column(name="cid")
    private String customerId;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="orderRecordPK.customer")
    @Cascade(CascadeType.ALL)
    private Set<OrderRecord> orderRecords = new HashSet<OrderRecord>();

    ...
    constructor, other fields, getters and setters
}    

OrderRecord.java

@Entity
@Table(name="orders")
public class Order implements Serializable {
    @EmbeddedId
    private OrderRecordPK orderRecordPK;

    ...
    constructor, other fields, getters and setters
}

OrderRecordPK.java

@Embeddable
public class OrderRecordPK implements Serializable{
    @Column(name="order_id")
    private int orderId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="customer_id", nullable=false)
    private Customer customer;

    ...
    constructor, other fields, getters and setters
}


No comments:

Post a Comment