表:person
id (pk)
first_name
last_name
实体:
@Entity
@Table(name="person")
public class Person {
@Id
@Column(name="id")
private String id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="birthDate")
private String birthDate;
@Column(name="detail")
private String detail;
}
表:activity
id(pk)
name;
实体:
@Entity
@Table(name="activity")
public class Activity {
@Id
@Column(name="id")
private String id;
@Column(name="name")
private String name;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="activity_id")
private List<PersonRole> personRoleList;
}
表:person_role
activity_id
person_id
role_name
pk(activity_id,person_id)
实体:
@Entity
@Table(name="person_role")
public class PersonRole {
@Id
PersonRolePK personRolePk;
// private String personName; /* I want this value to be loaded form person table using the person_id when a PersonRole is reader from database */
@Column(name="role_name")
private String roleName;
}
@Embeddable
public class PersonRolePK implements Serializable
{
public static final long serialVersionUID = 1L;
@Column(name="activity_id")
public String activityId;
@Column(name="person_id")
public String personId;
}
当我在数据库中存储数据时,这对我很有用
当我想要数据库中的Activity
时,它也按预期工作并加载所有相关的PersonRole现在,我想在加载PersonRole时从表personName
填充类PersonRole
(注释)的person
字段。
我阅读了有关@SecondaryTable
注释的内容并与之进行了接触。
但问题是这个http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2235)显示的所有教程和文档 如果我想映射辅助表,那么必须在两个表中具有相同数量的主键字段(如果是复合键),并且将使用@PrimaryKeyJoinColumn映射那些字段
但在我的情况下,没有必要使用多个密钥,因为Person有单个主键
那么有没有办法将包含复合主键的表映射到包含单个主键的表以使用@SecondaryTable
?
或,
有没有其他好方法可以达到我想要的目的。?
答案 0 :(得分:1)
通常在这种情况下,我会在Activity和Person pojo中拥有OneToMany关系。在PersonRole pojo中,您将为每个Activity和Person提供ManyToOne关系,这样您就可以获得所需的所有数据,而无需复制数据(人名)。
在Person pojo中添加OneToMany。
Set<PersonRole> personRoles = new HashSet<PersonRoles>();
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person")
public Set<PersonRole> getPersonRoles() {
return this.personRoles;
}
public void setPersonRoles(Set<PersoneRole> personRoles) {
this.personRoles = personRoles;
}
在PersonRole pojo中添加ManyToOne关系。
Private Person person;
Private Activity activity;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "person_id")
public Person getPerson() {
return this.person;
}
public void setPerson(Person person) {
this.person = person;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "activity_id")
public Activity getActivity() {
return this.activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
现在,您应该可以在查询“活动”时从“人”中获取该名称。