Hibernate 一对多配置(注解)
2018-07-25 本文已影响16人
tingshuo123
商品与评论关系的一对多
表结构设计
t_goods:

t_comment:

商品(一的一方)
package com.project.bean;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* 商品与评论的一对多关系
* @author wqj24
*
*/
@Entity
@Table(name="t_goods")
public class GoodsBean {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="g_id")
private int id;
@Column(name="g_name")
private String name;
@Column(name="g_price")
private double price;
@Column(name="g_type")
private String type;
/*
* mappedBy:在一对多关系中,一的一方写,表示有对方维护关联关系,值应该为对方的对象变量
* cascade:开启级联
*/
@OneToMany(mappedBy="goods", cascade=CascadeType.ALL)
private Set<CommentBean> comSet;
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;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Set<CommentBean> getComSet() {
return comSet;
}
public void setComSet(Set<CommentBean> comSet) {
this.comSet = comSet;
}
@Override
public String toString() {
return "GoodsBean [id=" + id + ", name=" + name + ", price=" + price + ", type=" + type + ", comSet=" + comSet
+ "]";
}
}
商品的评论(多的一方)
package com.project.bean;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_stu")
public class StudentBean {
private int id;
private String name;
private ClassBean cla = new ClassBean();;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="s_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="s_name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
//指定外键的名称
@JoinColumn(name="o_u_id")
public ClassBean getCla() {
return cla;
}
public void setCla(ClassBean cla) {
this.cla = cla;
}
@Override
public String toString() {
return "StudentBean [id=" + id + ", name=" + name + "]";
}
}