JPA双向一对一关联关系@OneToOne

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36722039/article/details/81056552

Department.class

package com.jpa.helloworld;

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

@Table(name="DEPARTMET")
@Entity
public class Department {

	private Integer depId;

	private String depName;

	private Manager mar;

	@GeneratedValue
	@Column(name="DEP_ID")
	@Id
	public Integer getDepId() {
		return depId;
	}

	public void setDepId(Integer depId) {
		this.depId = depId;
	}

	@Column(name="DEP_NAME")
	public String getDepName() {
		return depName;
	}

	public void setDepName(String depName) {
		this.depName = depName;
	}

	//这是维护关联关系的一方
	//在这一边加入外键列,列名为MAR_ID,并且将该列设置为唯一约束
	@JoinColumn(name="MAR_ID",unique=true)
	@OneToOne
	public Manager getMar() {
		return mar;
	}

	public void setMar(Manager mar) {
		this.mar = mar;
	}

}

Manager.class

package com.jpa.helloworld;

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

@Table(name="MANAGER")
@Entity
public class Manager {

	private Integer marId;

	private String marName;

	private Department dept;

	@GeneratedValue
	@Id
	@Column(name="MAR_ID")
	public Integer getMarId() {
		return marId;
	}

	public void setMarId(Integer marId) {
		this.marId = marId;
	}

	@Column(name="MAR_NAME")
	public String getMarName() {
		return marName;
	}

	public void setMarName(String marName) {
		this.marName = marName;
	}

	//这是不维护关联关系的一方
	//添加mappedBy属性,则该方不维护关联关系
	//mappedBy的属性为维护关联关系一方的属性名
	@OneToOne(mappedBy="mar")
	public Department getDept() {
		return dept;
	}
	public void setDept(Department dept) {
		this.dept = dept;
	}

}


展开阅读全文

没有更多推荐了,返回首页