注解:【基于主键的】Hibernate1->1关联

参考:http://blog.sina.com.cn/s/blog_674b23220100hjb5.html

Husband.java

package org.crazyit.app.domain;

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

@Entity
public class Husband {
@Id
@GeneratedValue // 主键生成器
private int id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn // 这个注解只能写在主(生成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;
}
}

Wife.java

package org.crazyit.app.domain;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Wife {
@Id
@GenericGenerator(name = "pkGenerator", strategy = "foreign", parameters = {
@Parameter(name = "property", value = "husband") })
@GeneratedValue(generator = "pkGenerator")
// wife的ID是根据husband的ID来赋值的,这里需要设置ID生成器的策略为foreign,参数中指定wife的ID是使用husband对象中的ID
private int id;
private String name;

@OneToOne(cascade = CascadeType.ALL, mappedBy = "wife")
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 void setHusband(Husband husband) {
this.husband = husband;
}

public Husband getHusband() {
return husband;
}
}

上一篇:JRE和JDK


下一篇:atitit  验证码理论与概览与 验证码规范 解决方案.docx