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.
使用类一级的 @SecondaryTable 或
@SecondaryTables 注解可以实现单个实体到多个表的映射。
使用 @Column 或者 @JoinColumn
注解中的 table 参数可指定某个字段所属的特定表。
@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.
在上面这个例子中,name保存在MainCat表中,
storyPart1保存在Cat1表中,
storyPart2保存在Cat2表中。
Cat1表通过外键cat_id和MainCat表关联,
Cat2表通过id字段和MainCat表关联
(和MainCat的id字段同名)。
对storyPart2字段还定义了唯一性约束。
Check out the JBoss EJB 3 tutorial or the Hibernate Annotations
unit test suite for more examples.
在JBoss EJB 3指南和Hibernate Annotations单元测试代码中还有更多的例子。