Multi-Table Entity in Hibernate

Most entities of mine refer to a single table. But when an entity looks at more than one table to collect its attributes, Hibernate provides a handy annotation for binding in a second table — @SecondaryTable.

Example:

@Entity
@Table(name = "barn_meta")
@SecondaryTable(name = "barn", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "barn_id") })
public class Barn {
    @Id
    @GeneratedValue
    @Column(nullable = false, name = "barn_id")
    private int id;

    @Column(nullable = true, name = "name")
    private String name;

    // field comes from the barn table
    @Column(nullable = false, name = "barn_plot_number", table = "barn")
    private int barnPlotNumber;

    /* ... constructors, methods, etc. */
}

In this example, the barn_meta table refers to the barn table through barn_meta.barn_id = barn.id. The default table is defined in the @Table annotation, so fields which come from a secondary table must include table in the @Column annotation.