6.Hibernate单向的多对一 关联映射
1.创建如下项目结构
2.在项目的src下创建hibernate.cfg.xml主配置文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" > 3 <hibernate-configuration> 4 <session-factory> 5 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 6 <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> 7 <property name="connection.username">scott</property> 8 <property name="connection.password">tiger</property> 9 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 10 <property name="show_sql">true</property> 11 <property name="format_sql">true</property> 12 13 <mapping resource="com/entity/Dept.hbm.xml"/> 14 <mapping resource="com/entity/Emp.hbm.xml"/> 15 </session-factory> 16 </hibernate-configuration>
3.在项目的src下的com.entity包下创建Dept.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.entity; 2 3 public class Dept { 4 /** 5 * 部门编号 6 */ 7 private int deptno; 8 /** 9 * 部门名称 10 */ 11 private String dname; 12 /** 13 * 部门位置 14 */ 15 private String loc; 16 public Dept() { 17 } 18 public Dept(int deptno, String dname, String loc) { 19 this.deptno = deptno; 20 this.dname = dname; 21 this.loc = loc; 22 } 23 public int getDeptno() { 24 return deptno; 25 } 26 public void setDeptno(int deptno) { 27 this.deptno = deptno; 28 } 29 public String getDname() { 30 return dname; 31 } 32 public void setDname(String dname) { 33 this.dname = dname; 34 } 35 public String getLoc() { 36 return loc; 37 } 38 public void setLoc(String loc) { 39 this.loc = loc; 40 } 41 @Override 42 public String toString() { 43 return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc 44 + "]"; 45 } 46 47 48 }
4.在项目的src下的com.entity包下创建Emp.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.entity; 2 3 import java.util.Date; 4 5 public class Emp { 6 /** 7 * 员工编号 8 */ 9 private Integer empno; 10 /** 11 * 员工姓名 12 */ 13 private String ename; 14 /** 15 * 员工工作 16 */ 17 private String job; 18 /** 19 * 员工领导编号 20 */ 21 private Integer mgr; 22 /** 23 * 员工雇佣日期 24 */ 25 private Date hiredate; 26 /** 27 * 员工工资 28 */ 29 private Integer sal; 30 /** 31 * 员工奖金 32 */ 33 private Integer comm; 34 /** 35 * 部门外键 36 * 引入部门对象 37 */ 38 private Dept dept; 39 public Emp() { 40 super(); 41 } 42 public Emp(Integer empno, String ename, String job, Integer mgr, 43 Date hiredate, Integer sal, Integer comm, Dept dept) { 44 this.empno = empno; 45 this.ename = ename; 46 this.job = job; 47 this.mgr = mgr; 48 this.hiredate = hiredate; 49 this.sal = sal; 50 this.comm = comm; 51 this.dept = dept; 52 } 53 54 public Integer getEmpno() { 55 return empno; 56 } 57 public void setEmpno(Integer empno) { 58 this.empno = empno; 59 } 60 public String getEname() { 61 return ename; 62 } 63 public void setEname(String ename) { 64 this.ename = ename; 65 } 66 public String getJob() { 67 return job; 68 } 69 public void setJob(String job) { 70 this.job = job; 71 } 72 public Integer getMgr() { 73 return mgr; 74 } 75 public void setMgr(Integer mgr) { 76 this.mgr = mgr; 77 } 78 public Date getHiredate() { 79 return hiredate; 80 } 81 public void setHiredate(Date hiredate) { 82 this.hiredate = hiredate; 83 } 84 public Integer getSal() { 85 return sal; 86 } 87 public void setSal(Integer sal) { 88 this.sal = sal; 89 } 90 public Integer getComm() { 91 return comm; 92 } 93 public void setComm(Integer comm) { 94 this.comm = comm; 95 } 96 public Dept getDept() { 97 return dept; 98 } 99 public void setDept(Dept dept) { 100 this.dept = dept; 101 } 102 @Override 103 public String toString() { 104 return "Emp [comm=" + comm + ", dept=" + dept + ", empno=" + empno 105 + ", ename=" + ename + ", hiredate=" + hiredate + ", job=" 106 + job + ", mgr=" + mgr + ", sal=" + sal + "]"; 107 } 108 109 110 111 112 113 114 }
5.在项目的src下的com.entity包下创建Dept.hbm.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 3 <hibernate-mapping> 4 <class name="com.entity.Dept" table="DEPT" schema="SCOTT"> 5 <!-- 主键配置 --> 6 <id name="deptno" type="java.lang.Integer" column="DEPTNO"> 7 <!-- 主键由应用程序负责生成 --> 8 <generator class="assigned"/> 9 </id> 10 <!-- 部门名称 --> 11 <property name="dname" type="java.lang.String" column="DNAME"/> 12 13 <!-- 部门位置 --> 14 <property name="loc" type="java.lang.String" column="LOC"/> 15 </class> 16 </hibernate-mapping>
6.在项目的src下的com.entity包下创建Emp.hbm.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 3 <hibernate-mapping> 4 <class name="com.entity.Emp" table="EMP" schema="scott"> 5 <id name="empno" type="java.lang.Integer" column="EMPNO"> 6 <generator class="assigned"/> 7 </id> 8 <property name="ename" type="java.lang.String" column="ENAME"/> 9 <property name="job" type="java.lang.String" column="JOB"/> 10 <property name="mgr" type="java.lang.Integer" column="MGR"/> 11 <property name="hiredate" type="java.util.Date" column="HIREDATE"/> 12 <property name="sal" type="java.lang.Integer" column="SAL"/> 13 <property name="comm" type="java.lang.Integer" column="COMM" not-null="false" /> 14 15 <!-- 多对一映射:name是emp中外键字段引用的对象,class是对象的类型,column是数据库中对应的外键列字段名 --> 16 <many-to-one name="dept" class="com.entity.Dept" column="DEPTNO"/> 17 </class> 18 </hibernate-mapping>
7.在项目的src下的com.util包下创建HibernateUtil.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.util; 2 3 import org.hibernate.HibernateException; 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.cfg.Configuration; 7 8 public class HibernateUtil { 9 /** 10 * 创建线程池来管理Session 11 */ 12 private static ThreadLocal<Session> thread=new ThreadLocal<Session>(); 13 /** 14 * 创建读取配置文件的对象 15 */ 16 private static Configuration config=null; 17 /** 18 * 创建获取Session的工厂 19 */ 20 private static SessionFactory factory=null; 21 22 /** 23 * 读取配置文件 24 */ 25 static{ 26 try { 27 config=new Configuration().configure("/hibernate.cfg.xml"); 28 factory=config.buildSessionFactory(); 29 } catch (HibernateException e) { 30 System.out.println("读取配置文件或创建SessionFactory失败!"); 31 e.printStackTrace(); 32 } 33 } 34 35 /** 36 * 获取session 37 * @return 38 */ 39 public static Session getSession(){ 40 Session session=thread.get(); 41 if(session==null){ 42 session=factory.openSession(); 43 thread.set(session); 44 } 45 return session; 46 } 47 48 /** 49 * 关闭Session 50 */ 51 public static void closeSession(){ 52 Session session=thread.get(); 53 thread.set(null); 54 session.close(); 55 } 56 57 58 }
8.在项目的src下的com.dao包下创建EmpDao.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.dao; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 import java.util.List; 7 import java.util.logging.SimpleFormatter; 8 9 import org.hibernate.Query; 10 import org.hibernate.Session; 11 import org.hibernate.Transaction; 12 13 import com.entity.Dept; 14 import com.entity.Emp; 15 import com.util.HibernateUtil; 16 17 public class EmpDao { 18 19 public static void main(String[] args) { 20 System.out.println("--------------------1.保存:1部门和2员工-----3条sql------------------"); 21 //saveEmp(); 22 System.out.println("----------------2.根据部门编号,查询该部门下的所有员工--2条sql--------------"); 23 //getEmpByDeptNo(1); 24 System.out.println("----------------3.查询所有员工--5条sql--------------"); 25 //getEmp(); 26 System.out.println("----------------4.删除--------------------------------------"); 27 //deleteEmp(1); 28 29 System.out.println("-----------------5.修改-----2个sql---------------------"); 30 updateEmp(2); 31 32 } 33 /** 34 * 5.修改 35 * @param i 36 */ 37 private static void updateEmp(int id) { 38 Session session=HibernateUtil.getSession(); 39 //2.开启事务 40 Transaction tx=session.beginTransaction(); 41 //查单条 42 Emp emp=(Emp) session.get(Emp.class, id); 43 if(emp!=null){ 44 emp.setEname("小猪"); 45 System.out.println("修改成功"); 46 }else{ 47 System.out.println("该条数据不存在"); 48 } 49 tx.commit(); 50 HibernateUtil.closeSession(); 51 52 } 53 /** 54 * 4.删除 55 * @param id 56 */ 57 private static void deleteEmp(int id) { 58 Session session=HibernateUtil.getSession(); 59 //2.开启事务 60 Transaction tx=session.beginTransaction(); 61 //查单条 62 Emp emp=(Emp) session.get(Emp.class, id); 63 if(emp!=null){ 64 session.delete(emp); 65 System.out.println("删除成功"); 66 }else{ 67 System.out.println("该条数据不存在"); 68 } 69 tx.commit(); 70 HibernateUtil.closeSession(); 71 72 } 73 /** 74 * -3.查询所有员工--2条sql 75 * 如果会报出: Null value was assigned to a property of primitive type setter of com.entity.Emp.comm异常 76 * 表示comm奖金字段为null,映射是Integer类型,而实体类里是int类型,int基本数据类型值没有null,所以报错 77 * 解决方法:将实体类所有字段数据类型改为引用数据类型 78 */ 79 private static void getEmp() { 80 Session session=HibernateUtil.getSession(); 81 String hql="from Emp"; 82 Query query=session.createQuery(hql); 83 List<Emp> list=query.list(); 84 for (Emp emp : list) { 85 System.out.println("部门编号:"+emp.getDept().getDeptno()+"\t部门名称:"+emp.getDept().getDname()+"\t员工姓名:"+emp.getEname()); 86 } 87 88 HibernateUtil.closeSession(); 89 90 } 91 /** 92 * 2.根据部门编号,查询该部门下的所有员工 93 * 2条sql 94 * @param i 95 */ 96 private static void getEmpByDeptNo(int id) { 97 //1.开启Session 98 Session session=HibernateUtil.getSession(); 99 100 String hql="from Emp e where e.dept.deptno=:pdeptno"; 101 Query query=session.createQuery(hql); 102 query.setParameter("pdeptno", id); 103 List<Emp> list=query.list(); 104 for (Emp emp : list) { 105 System.out.println(emp); 106 } 107 //5.关闭Session 108 HibernateUtil.closeSession(); 109 110 } 111 /** 112 * 1.保存:1部门和2员工-----3条sql 113 */ 114 private static void saveEmp() { 115 //1.开启Session 116 Session session=HibernateUtil.getSession(); 117 118 //2.开启事务 119 Transaction tx=session.beginTransaction(); 120 121 //3.执行操作 122 //创建部门对象 123 Dept dept=new Dept(1, "质控部", "中部"); 124 125 //保存dept对象 126 session.save(dept); 127 System.out.println("Dept保存成功"); 128 129 Date date=null; 130 try { 131 date = new SimpleDateFormat("yyyy-MM-dd").parse("2013-3-3"); 132 } catch (ParseException e) { 133 e.printStackTrace(); 134 } 135 136 //创建员工对象 137 Emp emp1=new Emp(1, "holly", "教员", 2, date, 2300, 200, dept); 138 Emp emp2=new Emp(2, "猪猪", "领导", 1, date, 3000, 200, dept); 139 140 //保存Emp对象 141 session.save(emp1); 142 143 //保存Emp对象 144 session.save(emp2); 145 System.out.println("Emp保存成功"); 146 147 //4.提交事务 148 tx.commit(); 149 150 //5.关闭Session 151 HibernateUtil.closeSession(); 152 } 153 154 }
9.结果自己验证...