hibernate Annotation一对一双向外键关联

hibernate中一对一双向外键关联注解配置如下:

(1)Wife类

package com.yy.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity(name="wife1")
public class Wife {

	private Husband husband;
	private int id;
	private String name;
	
	@OneToOne(mappedBy="wife")
	public Husband getHusband() {
		return husband;
	}
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
}
为了避免表结构的冗余,其中mappedBy是必须设置的,即参考对方wife属性。
(2)Husband类

package com.yy.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity(name="husband1")
public class Husband {

	private int id;
	private String name;
	
	private Wife wife;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	
	@OneToOne
	@JoinColumn(name="wifeId")
	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;
	}
}
(3)生成的数据表

mysql> desc husband1;
+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| name   | varchar(255) | YES  |     | NULL    |                |
| wifeId | int(11)      | YES  | MUL | NULL    |                |
+--------+--------------+------+-----+---------+----------------+

mysql> desc wife1;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+



你可能感兴趣的:(Hibernate,onetoone)