Hibernate example 2 – one-to-many associations

Just put an example of how to use one-to-many associations with Hibernate on Github:

https://github.com/hedleyproctor/hibernate-one-to-many

Shows two examples of a one-to-many relationship between entities:

  1. Unordered one-to-many between Customer and Address.
  2. Ordered one-to-many between Customer and PaymentCard.

The unordered association uses the normal setup where the “many” side of the association owns the relationship and is responsible for updating the database, so in the Address class, it declares the ManyToOne association:

@Entity
public class Address {
 
    private Customer customer;
 
    @ManyToOne
    public Customer getCustomer() {
        return customer;
    }
 
    // more code here...
}

The Customer defers to this mapping, so in the Customer class you have:

    private Set<Address> addresses = new HashSet<Address>();
 
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    public Set<Address> getAddresses() {
        return addresses;
    }

By contrast, the ordered mapping between the Customer and the PaymentCard needs to be owned by the Customer, because only the customer knows the ordering of the cards in the list. Hence this is mapped in the Customer class:

    private List<PaymentCard> paymentCards = new ArrayList<PaymentCard>();
 
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "CUSTOMER_ID", nullable = false)
    @OrderColumn(name = "CARD_INDEX")
    // Order column wasn't in JPA 1, so you'd previously have had: 
    // @org.hibernate.annotations.IndexColumn(name = "CARD_INDEX")
    public List<PaymentCard> getPaymentCards() {
		return paymentCards;
    }

Then the PaymentCard just defers to this mapping:

private Customer customer;
 
@ManyToOne
@JoinColumn(name = "CUSTOMER_ID", nullable = false, insertable = false, updatable = false)
public Customer getCustomer() {
    return customer;
}

If you want more info about one-to-many associations, check out Chapter 8 of the Hibernate docs:

http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch08.html

This entry was posted in Hibernate, Java and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

502,541 Spambots Blocked by Simple Comments

HTML tags are not allowed.