hibernate one2one
Posted 跳刀玛利亚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate one2one相关的知识,希望对你有一定的参考价值。
package com.bjsxt.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
public class Husband {
@Id
@GeneratedValue
private int id;
private String name;
@OneToOne // (1 一对一关系 @OneToOne(mappedBy="husband")//在对应的 wife表中husband_id 对应当前主键id)
//(2 mappedBy = "husband"-------对应的是 Wife类里面的 成员变量Husband husband--变量名 而不是getter方法名)
//(3 Wife 类 里面有对应的 Husband 成员变量 并却是 @OneToOne 关系)
@JoinColumn(name="wife_id") //joinColumn 在当前表中 添加字段 (wife_id) 对应的外键id 为 wife里的主键id
private Wife wife;
public int getId() {
return id;
}
public String getName() {
return name;
}
public Wife getWife() {
return wife;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}
``````````````````````````````````````````````````````
package com.bjsxt.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
@Entity
public class Wife {
@Id
@GeneratedValue
private int id;
private String name;
@OneToOne
private Husband husband;
public Husband getHusband() {
return husband;
}
public void setHusband(Husband husband) {
this.husband = husband;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
以上是关于hibernate one2one的主要内容,如果未能解决你的问题,请参考以下文章
Spring和Hibernate的注解整合 hibernate3和hibernate4/5的区别