@OneToMany或@ManyToOne的用法-annotation关系映射篇

package com.pandy.ssh4.domian;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "ParentOne")
public class ParentOne {
private int p1Id;
private String p1Name;
private String p1Desc;

private Set<ParentTwo> parentTwos;

@Id
@GeneratedValue
@Column(name = "p1_id", unique = true, nullable = false)
public int getP1Id() {
return p1Id;
}

public void setP1Id(int p1Id) {
this.p1Id = p1Id;
}

@Column(name = "p1_name", length = 100, nullable = true)
public String getP1Name() {
return p1Name;
}

public void setP1Name(String p1Name) {
this.p1Name = p1Name;
}

@Column(name = "p1_desc", length = 100, nullable = true)
public String getP1Desc() {
return p1Desc;
}

public void setP1Desc(String p1Desc) {
this.p1Desc = p1Desc;
}

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parentOne")
// 这里配置关系,并且确定关系维护端和被维护端。mappBy表示关系被维护端,只有关系端有权去更新外键。
// 这里还有注意OneToMany默认的加载方式是赖加载。当看到设置关系中最后一个单词是Many,那么该加载默认为懒加载
public Set<ParentTwo> getParentTwos() {
return parentTwos;
}

public void setParentTwos(Set<ParentTwo> parentTwos) {
this.parentTwos = parentTwos;
}

}



package com.pandy.ssh4.domian;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "ParentTwo")
public class ParentTwo {
private int p2Id;
private String p2Name;
private String p2Remark;

private ParentOne parentOne;

@Id
@GeneratedValue
@Column(name = "p2_id", nullable = false, unique = true)
public int getP2Id() {
return p2Id;
}

public void setP2Id(int p2Id) {
this.p2Id = p2Id;
}

@Column(name = "p2_name", nullable = true)
public String getP2Name() {
return p2Name;
}

public void setP2Name(String p2Name) {
this.p2Name = p2Name;
}

@Column(name = "p2_remark", nullable = true)
public String getP2Remark() {
return p2Remark;
}

public void setP2Remark(String p2Remark) {
this.p2Remark = p2Remark;
}

// 这里设置JoinColum设置了外键的名字,并且ParentTwo是关系维护端
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "p1_id")
public ParentOne getParentOne() {
return parentOne;
}

public void setParentOne(ParentOne parentOne) {
this.parentOne = parentOne;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值