一对一关联关系中的两端实体为一一对应
例如:公民与身份证、学生与档案、丈夫与妻子等
例题:采用外键法映射客户与邮箱之间的单向一对一
客户表为t_users,邮箱表为t_email
选择t_users为主表, t_email为从表
1.编写实体类 Users
@Entity
@Table(name = “t_users”)
public class Users implements java.io.Serializable {
private Integer usersId;
private String userName;
private Email email;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "users_id")
public Integer getUsersId() {
return usersId;
}
public void setUsersId(Integer usersId) {
this.usersId = usersId;
}
@Column(name = "users_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@OneToOne(targetEntity = Email.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "email_id", insertable = true, unique = true)
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
}
2.编写实体类 Email
@Entity // 在类声明上方加入Entity注解,表示一个实体类,对应数据库的t_email表
@Table(name = “t_email”)
public class Email implements java.io.Serializable {
private Integer emailId;
private String emailName;
private Users users;
public Email() {
}
public Email(String emailName) {
this.emailName = emailName;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 注解定义主键生成方式,自动增长列
@Column(name = "email_id")
public Integer getEmailId() {
return emailId;
}
public void setEmailId(Integer emailId) {
this.emailId = emailId;
}
@Column(name = "email_name")
public String getEmailName() {
return emailName;
}
public void setEmailName(String emailName) {
this.emailName = emailName;
}
@OneToOne(mappedBy = "email", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
}
3.编写测试文件 DemoOneToOne
public class DemoOneToOne {
public static void main(String[] args) {
Session s = HibernateSessionFactory.getSession();
Transaction t = s.beginTransaction();
Users u = new Users();
u.setUserName("赵云");
Email e = new Email("1014867116@qq.com");
u.setEmail(e);
s.save(u);
t.commit();
s.close();
System.out.println("操作成功!");
}
}
4.配置文件