本文共 2266 字,大约阅读时间需要 7 分钟。
package cn.edu.hpu.one2one;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.OneToOne;@Entitypublic class Husband { private int id; private String name; private Wife wife; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @OneToOne @JoinColumn(name="wifeid") public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package cn.edu.hpu.one2one;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.OneToOne;@Entitypublic class Wife { private int id; private String name; private Husband husband; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } @OneToOne public Husband getHusband() { return husband; } public void setHusband(Husband husband) { this.husband = husband; } public String getName() { return name; } public void setName(String name) { this.name = name; } }生成的建表语句: alter table Husband drop foreign key FKAEEA401BC6294CED alter table Wife drop foreign key FK29233185D75BEA drop table if exists Husband drop table if exists Wife create table Husband ( id integer not null auto_increment, name varchar(255), wifeid integer, primary key (id) ) create table Wife ( id integer not null auto_increment, name varchar(255), husband_id integer, primary key (id) ) alter table Husband add index FKAEEA401BC6294CED (wifeid), add constraint FKAEEA401BC6294CED foreign key (wifeid) references Wife (id) alter table Wife add index FK29233185D75BEA (husband_id), add constraint FK29233185D75BEA foreign key (husband_id) references Husband (id) 双向关联在数据库中只需一边设置外键就行了,所以wife的husband_id就可以不要 mappedBy="wife"告诉hibernate,Wife和husband之间是一个1对1的关联, 对方husband类的wife属性已经做映射了,你就不用管我生成的外键的关联了 对方那边是主导,你不用管我这边的设置 这个时候wife建表语句中就没有husband_id属性了 凡是双向关联必设mappedBy 所以wife实体类注解写成: @OneToOne(mappedBy="wife") public Husband getHusband() { return husband; }
生成的表中wife就没有husband_id字段了
转载请注明出处: