JPA学习笔记八 双向一对一

package com.yjj.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "t_department")
@Entity
public class Department {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    //省略getter,setter
}

package com.yjj.entity;

import javax.persistence.*;

/**
 * order当成manager
 */
@Table(name = "t_manager")
@Entity
public class Manager {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @JoinColumn(name="departmentId")
    @OneToOne
    private Department department;

 //省略getter,setter
}

看自动建的表
t_manager表


image.png

t_department表


image.png

如果我把JoinColumn和OneToOne放在Department实体类,且维护一个Manager

@Table(name = "t_department")
@Entity
public class Department {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @JoinColumn(name = "managerId")
    @OneToOne
    private Manager manager;
}
@Table(name = "t_manager")
@Entity
public class Manager {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
}

department表 多了一个managerId


image.png

双向的就双方各维护一个对方,会怎么样。。。
那就都有


image.png

image.png

那我加一个mappedBy呢

@Table(name = "t_manager")
@Entity
public class Manager {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @OneToOne(mappedBy = "manager")
    private Department department;
}
@Table(name = "t_department")
@Entity
public class Department {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    @JoinColumn(name = "managerId")
    @OneToOne
    private Manager manager;
}
image.png

image.png

那如果我mappedBy写成department呢
会报错。
那就是说,mappedBy注解只能写自己咯

你可能感兴趣的:(JPA学习笔记八 双向一对一)