多对一(Many-to-One)
使用@ManyToOne批注来实现多对一关联。
@ManyToOne批注有一个名为targetEntity的参数,该参数定义了目标实体名,通常不需要定义该参数,因为在大部分情况下默认值(表示关联关系的属性类型)就可以很好的满足需求了。不过下面这种情况下这个参数就显得有意义了:使用接口作为返回值而不是常见的实体。
@ManyToOne(targetEntity=CompanyImpl.class)
@JoinColoumn(name=”COPM_ID”)
Public Company getCompany(){
return company;
}
多对一的配置方式有两种:(1)通过@JoinColoumn映像(2)通过关联表的方式来映像
(1)通过@JoinColoumn映射
SRD Framework中Company,Category例子:
Company:
@ManyToOne
@JoinColumn(name = "CATEGORY_OPTION_ID")
private Category category = null;
Category:
@DiscriminatorValue("Category")
public class Category extends Option {
}
(2)通过关联表映射
通过@JoinTable批注定义关联表,该关联表包含了指回实体表的外键(通过@JoinTable.joinColoumns)以及指向目标实体表的外键(通过@JoinTable.inverseJoinColoumns)
@Entity
@Table(name="Test_TreeType")
public class TreeType {
private Integer id;
private String name;
private ForestType forestType;
@ManyToOne(fetch = FetchType.LAZY)
@JoinTable(name="Test_Tree_Forest",
joinColumns = @JoinColumn(name="tree_id"),
inverseJoinColumns = @JoinColumn(name="forest_id") )
public ForestType getForestType() {// forestType的getter,setter方法必须在这里,否则会出错
return forestType;
}
public void setForestType(ForestType forestType) {
this.forestType = forestType;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
@Table(name="Test_ForestType")
public class ForestType {
private Integer id;
private String name;
private Set<TreeType> trees;
@OneToMany(mappedBy="forestType")
public Set<TreeType> getTrees() {// trees的getter,setter方法必须在这里,否则会出错
return trees;
}
public void setTrees(Set<TreeType> trees) {
this.trees = trees;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}