One(‘多’)
import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity public class Wife { private int id; private String name; private Husband husband; /** * wife的ID是根据husband的ID来赋值的,需设置ID生成器的策略为foreign * * 参数中指定wife的ID是使用husband对象中的ID */ @Id @GenericGenerator(name = "pkGenerator", strategy = "foreign", parameters = { @Parameter(name = "property", value = "husband") }) @GeneratedValue(generator = "pkGenerator") 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; } @OneToOne(cascade = CascadeType.ALL) public Husband getHusband() { return husband; } }
One(‘一’)
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 { private int id; private String name; private Wife wife; @Id @GeneratedValue public int getId() { return id; } public String getName() { return name; } // 该注解只能写在主(生成ID)的一端 @OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn 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; } }
时间: 2024-10-31 02:21:55