项目当前存在2张表account及Phone,两个表有各自的主键Id,Phone通过表内的account_id实现对account表的1对1,通过如下配置可完成OneToOne关系的构建
@Entity @Table(name = "account") public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "id", length = 40 ,insertable=false ,updatable=false) private String id; @OneToOne(fetch = FetchType.LAZY,optional = false,mappedBy="account") private Phone phone; public Account() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }
}
注意点是:在account表中mappyedBy不是填写account_id而是account,这个account并非是表明,而是体现account_id的功能,注解会自动为它加上_id并配对@Entity @Table(name = "phone") public class Phone implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "id", length = 40 ,insertable=false ,updatable=false) private String id;@OneToOne(cascade = CascadeType.ALL) @JoinColumn(name="account_id")private Phone phone; public Account() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }}