Monday, September 16, 2013

Hibernate one-to-many with child entity using id as primary key

Scenario: A customer can have multiple phones. The customer entity has cid as primary key, and the phone has phone_id as primary key

Database tables:

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

 CREATE TABLE phones (
    phone_id INT PRIMARY KEY,
    customer_id VARCHAR(8),
    number INT,
    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="customer")
    @Cascade(CascadeType.ALL)
    private Set<OrderRecord> phones = new HashSet<OrderRecord>();

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

Phone.java

@Entity
@Table(name="phones")
public class Phone implements Serializable {
    @Id
    @Column(name="phone_id")
    private int phoneId;

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

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

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


No comments:

Post a Comment