2.2.7. Mapping secondary tables
You can map a single entity bean to several tables using the
@SecondaryTable
or @SecondaryTables
class level annotations. To express that a column is in a particular table, use the table
parameter of @Column
or @JoinColumn
.
@Entity @Table(name="MainCat") @SecondaryTables({ @SecondaryTable(name="Cat1", pkJoinColumns={ @PrimaryKeyJoinColumn(name="cat_id", referencedColumnName="id") ), @SecondaryTable(name="Cat2", uniqueConstraints={@UniqueConstraint(columnNames={"storyPart2"})}) }) public class Cat implements Serializable { private Integer id; private String name; private String storyPart1; private String storyPart2; @Id @GeneratedValue public Integer getId() { return id; } public String getName() { return name; } @Column(table="Cat1") public String getStoryPart1() { return storyPart1; } @Column(table="Cat2") public String getStoryPart2() { return storyPart2; }
In this example,
name
will be in MainCat
. storyPart1
will be in Cat1
and storyPart2
will be in Cat2
. Cat1
will be joined to MainCat
using the cat_id
as a foreign key, and Cat2
using id
(ie the same column name, the MainCat
id column has). Plus a unique constraint on storyPart2
has been set.
Check out the JBoss EJB 3 tutorial or the Hibernate Annotations unit test suite for more examples.