我必须使用hibernate并且不太确定如何解决这个问题,我有2个表与1..n这样的关系:
------- TABLE_A ------- first_id (pk) second_id (pk) [other fields] ------- TABLE_B ------- first_id (pk)(fk TABLE_A.first_id) second_id (pk)(fk TABLE_A.second_id) third_id (pk) [other fields]
如何使用Hibernate ???
来管理它我不知道如何管理第二个表的主键...
答案 0 :(得分:15)
有一个例子与Hibernate reference documentation中的案例完全相似。就在这个例子之前,你会找到解释。以下是与您的问题相匹配的示例(用户是表A,而客户是表B):
@Entity
class Customer {
@EmbeddedId CustomerId id;
boolean preferredCustomer;
@MapsId("userId")
@JoinColumns({
@JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
@JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
})
@OneToOne User user;
}
@Embeddable
class CustomerId implements Serializable {
UserId userId;
String customerNumber;
//implements equals and hashCode
}
@Entity
class User {
@EmbeddedId UserId id;
Integer age;
}
@Embeddable
class UserId implements Serializable {
String firstName;
String lastName;
//implements equals and hashCode
}
注意:对于这两个表,有一个代理标识符要简单得多。除非你被迫处理遗留架构,否则请帮忙并使用代理键。
答案 1 :(得分:3)
使用@PrimaryKeyJoinColumn
和@PrimaryKeyJoinColumns
注释。来自Hibernate manual:
@PrimaryKeyJoinColumn
注释确实表示实体的主键用作关联实体的外键值。
答案 2 :(得分:0)
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5478661842746845130L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
}
@Entity
public class Author {
@Id
@Column(name = "AUTHOR_ID", nullable = false)
private int authorId;
@Column(name = "ENABLED", nullable = false, length = 1)
private boolean enabled;
@OneToOne
@MapsId
@JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID", nullable = false, insertable = false, updatable = false)
User user;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}