hibernate基于注解的一对多关联使用@OneToOne注解。
注意:需要引入的为: javax.persistence.OneToOne
维护端(有外键方):
@Id
@GenericGenerator(name = "pkGenerator", strategy = "foreign",
parameters = { @Parameter(name = "property", value = "idCard") })
@GeneratedValue(generator = "pkGenerator")
@Column(name = "userId")
public int getUserId() {
return userId;
}
@OneToOne
@PrimaryKeyJoinColumn
@Cascade(CascadeType.ALL) // 设置级联操作
public IdCard getIdCard() {
return idCard;
}
被维护端(无外键方):
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idCardId")
public int getId() {
return Id;
}
@OneToOne(mappedBy = "idCard")
@Cascade(CascadeType.ALL)
@PrimaryKeyJoinColumn
public User getUser() {
return user;
}
假设有两个类:User(用户)与IdCard(身份证),一个用户对应一个身份证。
User 类 如下
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name = "user")
public class User {
private int userId;
private String username;
private IdCard idCard;
@Id
@GenericGenerator(name = "pkGenerator", strategy = "foreign",
parameters = { @Parameter(name = "property", value = "idCard") })
@GeneratedValue(generator = "pkGenerator")
@Column(name = "userId")
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@OneToOne
@PrimaryKeyJoinColumn
@Cascade(CascadeType.ALL) // 设置级联操作
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
}
IdCard 类 如下
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@Entity
@Table(name = "idCard")
public class IdCard {
private int Id;
private String idno;
private User user;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idCardId")
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
@Basic
@Column(name = "idno", nullable = false)
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
@OneToOne(mappedBy = "idCard")
@Cascade(CascadeType.ALL)
@PrimaryKeyJoinColumn
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}