欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OneToOne主键关联

程序员文章站 2022-04-22 16:10:27
...

首先来看表的关系:

表1:

Husband

husband_id<<pk>>

name


表2

Wife

wife_id <<pk>><<fk>>
name



Husband类

@Entity
public class Husband {
	@Id
	@GeneratedValue
	private int id;
	private String name;
	@OneToOne(cascade = CascadeType.ALL)
	@PrimaryKeyJoinColumn
	private Wife wife;

	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;
	}

	public Wife getWife() {
		return wife;
	}

	public void setWife(Wife wife) {
		this.wife = wife;
	}

}

 

Wife类

@Entity
public class Wife {
	@Id
	@GeneratedValue(generator = "myForeignGenerator")
	@org.hibernate.annotations.GenericGenerator(name = "myForeignGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "husband"))
	private int id;
	private String name;
	@OneToOne(optional = false, cascade = CascadeType.ALL)
	@PrimaryKeyJoinColumn
	private 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;
	}

	public Husband getHusband() {
		return husband;
	}

	public void setHusband(Husband husband) {
		this.husband = husband;
	}
}

 

wife类中的

@Id
 @GeneratedValue(generator = "myForeignGenerator")
 @org.hibernate.annotations.GenericGenerator(name = "myForeignGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "husband"))
 private int id;

 

定义了外键的生成策略,这样可以在级联插入时保持husband的主键和wife的外键(也是主键)相同。

 

@Test
	public void testOneToOnePK() {
		OneToOne.PK.Husband husband = new OneToOne.PK.Husband();
		OneToOne.PK.Wife wife = new OneToOne.PK.Wife();
		husband.setName("me");
		wife.setName("mywife");

		wife.setHusband(husband);
		session.beginTransaction();
		session.save(wife);//级联插入husband
		// session.save(husband);
		session.getTransaction().commit();
	}

 

 

相关标签: Hibernate