2.2、Hibernate用注解方式实现一对多、多对多关系

一、一对多关系

  1、在上一篇日志中用.xml配置文件项目基础上,再往lib目录先添加一个包-hibernate-jpa-2.0-api-1.0.0.Final.jar

  2、新建一个com.st.bean4 包,往包里面添加两个含有注解的类:

    a)、DeptBean2类:

 package com.st.bean4;

 import java.util.HashSet;
import java.util.Set; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table; import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator; @Entity //指定实体类
@Table(name="DEPT") //对应表的名称
@GenericGenerator(name="genID", strategy="increment") //声明主键生成策略
public class DeptBean2 {
@Id //指定主键
@GeneratedValue(generator="genID") //设定主键生成策略
@Column(name="ID") //指定类中的属性与表中的列的对应关系
private long id;
@Column(name="NAME") //指定类中的属性与表中的列的对应关系
private String name; @OneToMany //指定一对多关系
@Cascade(value={CascadeType.SAVE_UPDATE}) //设定级联关系
@JoinColumn(name="dept_id") //指定与本类主键所对应的外表的外键
private Set<EmployeeBean2> emp = new HashSet<EmployeeBean2>();
@Override
public String toString() {
return "DeptBean [id=" + id + ", name=" + name +"]";
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<EmployeeBean2> getEmp() {
return emp;
}
public void setEmp(Set<EmployeeBean2> emp) {
this.emp = emp;
}
}

    b)、EmployeeBean类:

 package com.st.bean4;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity //指定一个实体
@Table(name="employee") //指定表的名称
@GenericGenerator(name="genID", strategy="increment") //声明主键生成策略
public class EmployeeBean2 {
@Id //指定主键
@GeneratedValue(generator="genID") //设定主键生成策略
@Column(name="ID") //类中的属性和表中的列名的对应关系
private long id;
@Column(name="NAME")
private String name;
@Column(name="SEX")
private String sex;
@Column(name="JOB")
private String job;
@ManyToOne// 指定多对一关系 //指定多对一关系
@JoinColumn(name="DEPT_ID")
//一个员工对应于一个部门号,所以这里不用集合
private DeptBean2 dept ; //注意这个地方不要new对象,否则会无法运行
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public DeptBean2 getDept() {
return dept;
}
public void setDept(DeptBean2 dept) {
this.dept = dept;
}
@Override
public String toString() {
return "EmployeeBean [id=" + id + ", name=" + name + ", sex=" + sex
+ ", job=" + job + ", dept=" + dept
+ "]";
}
}

  3、在hibernate.cfg.xml文件中引入上面两个类的映射

          <mapping class="com.st.bean5.UserBean2" />
<mapping class="com.st.bean5.RoleBean2" />

  4、在BeanTest中添加相应的测试方法:

     @Test
public void bean4test1(){
Session session = HibernateTools.openSession();
Transaction tran = session.beginTransaction();
//首先在dept中新增一条数据,再关联的在employee中新增一条数据
//DeptBean2 dept = new DeptBean2();
//先读去dept中的数据,再在读取的基础上关联的在employee中新增一条数据
DeptBean2 dept = (DeptBean2) session.get(DeptBean2.class,1L); //1L代表主键
EmployeeBean2 emp = new EmployeeBean2();
//dept.setName("技术部");
emp.setName("陈泽俊");
emp.setSex("男");
emp.setJob("STM32");
dept.getEmp().add(emp);
session.save(dept);
//确认提交事物
tran.commit();
}

 

二、多对多关系

  1、新建一个com.st.bean4 包,往包里面添加两个含有注解的类

    a)、UserBean2:

 package com.st.bean5;
import java.util.HashSet;
import java.util.Set; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator; @Entity //实体
@Table(name="T_USER") //表名
@GenericGenerator(name="genID", strategy="increment") //声明主键生成策略
public class UserBean2 {
@Id //指定主键
@GeneratedValue(generator="genID") //设定主键生成策略
@Column(name="ID") //指定类的属性和表的字段的对应关系
private long id;
@Column(name="NAME")
private String name;
@Column(name="SEX")
private String sex;
@ManyToMany //指定多对多关系
@Cascade(value={CascadeType.SAVE_UPDATE}) //设置级联关系
@JoinTable(name="USER_ROLE", //指定第三张表
joinColumns={@JoinColumn(name="USER_ID")}, //本表与中间表的外键对应
inverseJoinColumns={@JoinColumn(name="ROLE_ID")}) //另一张表与第三张表的外键的对应关系
private Set<RoleBean2> role = new HashSet<RoleBean2>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Set<RoleBean2> getRole() {
return role;
}
public void setRole(Set<RoleBean2> role) {
this.role = role;
}
@Override
public String toString() {
return "UserBean [id=" + id + ", name=" + name + ", sex=" + sex
+ ", role=" + role + "]";
}
}

    b)、RoleBean类:

 package com.st.bean5;
import java.util.HashSet; import java.util.Set; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator; @Entity //实体
@Table(name="T_ROLE") //表名
@GenericGenerator(name="genID", strategy="increment")//声明主键生成策略
public class RoleBean2 {
@Id //主键
@GeneratedValue(generator="genID") //设置主键生成策略
@Column(name="ID") //类中的属性与表的字段的对应关系
private long id;
@Column(name="POST")
private String post;//职位
@Column(name="PAY")
private int pay; //薪资
@ManyToMany //多对多关系
@Cascade(value={CascadeType.SAVE_UPDATE}) //级联关系
@JoinTable(name="USER_ROLE", //中间表的名称
joinColumns={@JoinColumn(name="ROLE_ID")}, //本表与中间表的外键对应关系
inverseJoinColumns={@JoinColumn(name="USER_ID")}) //另一张表与中间表的外键的对应关系
private Set<UserBean2> user = new HashSet<UserBean2>(); public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public int getPay() {
return pay;
}
public void setPay(int pay) {
this.pay = pay;
}
public Set<UserBean2> getUser() {
return user;
}
public void setUser(Set<UserBean2> user) {
this.user = user;
}
@Override
public String toString() {
return "RoleBean [id=" + id + ", post=" + post + ", pay=" + pay + "]";
}
}

  2、在hibernate.cfg.xml中引入UserBean2和RoleBean2这两个类的映射:

          <mapping class="com.st.bean5.UserBean2" />
<mapping class="com.st.bean5.RoleBean2" />

  3、在BeanTest类中添加测试方法:

     @Test
public void bean5test1(){
// 获取一个会话
Session session = HibernateTools.openSession();
//开启一次事物
Transaction tran = session.beginTransaction();
UserBean2 user = new UserBean2();
// RoleBean2 role = (RoleBean2) session.get(RoleBean2.class,1L);
RoleBean2 role = new RoleBean2(); user.setName("汪文仕");
user.setSex("男"); role.setPost("博士");
role.setPay(10000); role.getUser().add(user);
session.save(role);
//确认提交事物
tran.commit();
}
@Test
public void bean5test2(){
// 获取一个会话
Session session = HibernateTools.openSession();
/* List<UserBean> list = session.createCriteria(UserBean.class).list();
for(UserBean user : list)
System.out.println(user);*/
String hql = "select new Map(u.name as name,u.sex as sex,r.post as post,r.pay as pay) from UserBean2 u join u.role r";
List<Map<String,Object>> list = session.createQuery(hql).list();
for(Map<String,Object> data : list)
System.out.println(data);
}

三、注意:

  1、引入了注解需要的jar包后要先删除Java EE 5 Library这个库,否则会两个jar包中的类产生冲突

  2、在多表操作时最好设置级联关系,不然对表操作时要先读取一个类的数据,再将新建的一个类的数据添加到这个类上才成功对三张表同时操作。

上一篇:toggle显示与隐藏切换


下一篇:python AES加密解密 pycryptodome