hibernate一对一双向外键关联

在Wife类里有Husband的引用,在Husband类里也有Wife类的引用。

Wife类:

package com.oracle.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class Wife {

    private int id;
    private String name;
    
    private int age;
    private Husband  husband;
    
    /**
     * 双向关联,必设mappedBy,
     * OneToOne告诉hibernate,wife和husband之间是一对一关联
     * mappedBy告诉hibernate,这个一对一的关联的定义被husband类的getWife的wife这个属性做了映射
     * 你在wife这个类里不用管我,告诉hibernate这个关系在对方那里是主导。
     * 若不指定,会在wife里设husband的id为wife的外键,也会在husband表里设定wife的id为外键,
     * 这样很不爽吧!在husband里设了mappedBy,就只在husband表里的wife上加外键,是双向的,在wife表里就不会再设一遍
     */
    @OneToOne(mappedBy="wife")
    @JoinColumn(name="husband")
    public Husband getHusband() {
        return husband;
    }
    public void setHusband(Husband husband) {
        this.husband = husband;
    }
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

Husband类:

package com.oracle.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToOne;

@Entity
public class Husband {

    private int id;
    private String name;
    private Wife  wife;    //wife的引用
    
    @Id    //主键id
    @GeneratedValue    //自动生成
    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;
    }
    
    @OneToOne    //一对一映射
    //JoinColumn指定映射到表里哪个字段,不指定会自动生成的外键名为wife_id
    @JoinColumn(name="wifeId")
    public Wife getWife() {
        return wife;
    }
    public void setWife(Wife wife) {
        this.wife = wife;
    }
}

生成的表:

生成表的语句:

create table Husband (
id integer not null auto_increment,
name varchar(255),
wifeId integer,
primary key (id)
)
23:05:51,025 DEBUG SchemaExport:377 -
create table Wife (
id integer not null auto_increment,
age integer not null,
name varchar(255),
primary key (id)
)
23:05:51,296 DEBUG SchemaExport:377 -
alter table Husband
add index FKAEEA401B796894FC (wifeId),
add constraint FKAEEA401B796894FC
foreign key (wifeId)
references Wife (id)

可以看到,只在husband表里加上了wife外键

原文地址:https://www.cnblogs.com/lihaoyang/p/4915841.html