主键一对一
数据库表结构
Student.java
1 @Entity 2 @Table(name = "student") 3 public class Student { 4 @Id 5 @Column(name = "id") 6 @GenericGenerator(name = "generator",strategy = "native") 7 @GeneratedValue(generator = "generator") 8 private int id; 9 10 @Column(name = "name") 11 private String name; 12 13 @OneToOne(cascade=CascadeType.ALL) 14 @PrimaryKeyJoinColumn//这个注解只能写在生成ID的一端 15 private IDCard idCard; 16 17 }
IDCard.java
1 @Entity 2 @Table(name = "idcard") 3 public class IDCard { 4 @Id 5 @GenericGenerator(name = "fkgenerator",parameters = {@Parameter(name = "property",value = "student")}, strategy = "foreign") 6 @GeneratedValue(generator = "fkgenerator") 7 private int id; 8 9 @Column(name = "num") 10 private String num; 11 12 @OneToOne(cascade=CascadeType.ALL,mappedBy = "idCard") 13 private Student student; 14 }
外键一对一
数据库表结构
Student.java
1 @Entity 2 @Table(name = "student") 3 public class Student { 4 @Id 5 @Column(name = "id") 6 @GenericGenerator(name = "generator",strategy = "uuid") 7 @GeneratedValue(generator = "generator") 8 private String id; 9 10 @Column(name = "name") 11 private String name; 12 13 @OneToOne(cascade=CascadeType.ALL) 14 @JoinColumn(name = "idcard") 15 private IDCard idCard; 16 }
IDCard.java
1 @Entity 2 @Table(name = "idcard") 3 public class IDCard { 4 @Id 5 @Column(name = "id") 6 @GenericGenerator(name = "generator",strategy = "uuid") 7 @GeneratedValue(generator = "generator") 8 private String id; 9 10 @Column(name = "num") 11 private String num; 12 13 @OneToOne(mappedBy = "idCard") 14 private Student student; 15 16 }