Posts Tagged ‘database’

Hibernate join tables for entity mapping – using them helps

Sunday, November 22nd, 2009

Over the last couple of years I have had various discussions about this with my colleagues. I myself favoured foreign keys relationships rather than join tables till a little while ago. If you’re not aware of how to do one or the other, the eamples below should explain that.

Consider a very simple parent child relationship. Every parent can have multiple children. Using a join table and JPA annotations, the model classes look something like this for unidirectional relationships: (I have excluded all fields not required for this example)
With join table …

@Entity
class Parent {
    @OneToMany
    @JoinTable(
            name="parents_children",
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="child_id")
    )
    private Set<Child> children
}

@Entity
class Child {
    //nothing
}

Without join table …

@Entity
class Parent {
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="parent_id")
    private Set<Child> children;
}

@Entity
class Child {
    // nothing
}

(more…)