Hibernate(五)
================================criteria(QBC)查询========================
QBC,(容器)又名对象查询:采用对象的方式(主要是criteria的实例)封装查询条件
criteria实例:SQL语句封装,以一个对象的形式展现
最大优势:动态查询
语法:
步骤:
1.创建criteria对象,createCriteria(Dept.class)
2.Restrictions 条件查询
3.添加条件实例,add
4.获取数据表的数据,list()
范例:
1.查询所有的部门
Criteria criteria = session.createCriteria(Dept.class);
List<Dept> list = criteria.list();
Restrictions:限制结果集内容--条件查询
常用方法:
1.Restrictions.eq(持久化类的属性名,字段的数值 )
2.Restrictions.in( )
3.Restrictions.like( )
4.Restrictions.and( )
5.Restrictions.ilike( ) 大小写不敏感
6.Restrictions.or( )
7.Restrictions.between( )
8.Restrictions.gt( )
9.Restrictions.ge( )
10.Restrictions.lt( )
11.Restrictions.le( )
12.Restrictions.disjunction( ) 多个条件(.add()形式的条件)
13.Restrictions.sqlRestriction( ) 多个条件(字符串形式的条件)
范例:
1.查询位置在"1楼"的部门
Criteria criteria = session.createCriteria(Dept.class);
Criterion critrion = Restrictions.eq("location", "1楼");
criteria = criteria.add(critrion);
List<Dept> list = criteria.list();
2.查询年龄大于20,或者用户名中含有”马“的记录
criteria.add(Restrictions.sqlRestriction(" age > 20 or username = '% 马 %' "));
排序:org.hibernate.criterion.Order
语法:
addOrder(Order.asc())
addOrder(Order.desc())
范例:先按工资升序排序,再按编号降序排序
List<Emp> list = session.createCriteria(Emp.class)
.add(Restrictions.gt("salary", 4000D))
.addOrder(Order.asc("salary"))
.addOrder(Order.desc("empNo")).list();
Example示例查询(QBE):
属性条件多,可以Example取代Restrictions。创建一个对象模板,以它为查询依据,查询出属性与之类似的对象
范例:所有年龄等于21的用户信息
分页:
方法:
setFirstResult(int firstResult)
setMaxResult(int maxResult)
范例:查询出工资最高的两名员工
List<Emp> list = session.createCriteria(Emp.class)
.add(Restrictions.isNotNull("salary"))
.addOrder(Order.desc("salary"))
.setFirstResult(0)
.setMaxResults(2).list();
查询唯一对象:
方法 说明 Query Criteria
list() 返回List集合 支持 支持
iterate() 返回Iterator迭代器,只查询出ID值。 支持 不支持
uniqueResult() 返回唯一对象 支持 支持
范例:查询工资最高的员工
Emp emp = (Emp) session.createCriteria(Emp.class)
.add(Restrictions.isNotNull("salary"))
.addOrder(Order.desc("salary"))
.setMaxResults(1)
.uniqueResult();
关联:建立内连接或迫切左外连接4
方法:
createCriteria()
createAlias()
范例:
1.List<Emp> list = session.createCriteria(Emp.class)
.add(Restrictions.ilike("empName", "a", MatchMode.ANYWHERE))
.createCriteria("dept")
.add(Restrictions.eq("deptName", "财务部").ignoreCase()) .list();
2.List<Emp> list = session.createCriteria(Emp.class, "e")
.createAlias("dept", "d")
.add(Restrictions.ilike("e.empName", "a",MatchMode.ANYWHERE))
.add(Restrictions.eq("d.deptName", "财务部").ignoreCase()).list();
投影:
方法:
org.hibernate.criterion.Projection接口
org.hibernate.criterion.Projections类
范例:
1.List<String> list = session.createCriteria(Dept.class)
.setProjection(Property.forName("deptName")).list();
2.List<Object[]> list = session
.createCriteria(Emp.class)
.setProjection(Projections.projectionList()
.add(Property.forName("empName"))
.add(Property.forName("hiredate"))).list();
分组:投影实现分组统计功能
方法:org.hibernate.criterion.Projections类提供了使用聚合函数查询的方法
方法 说明
1.Projections.groupProperty() 分组
2.Projections.rowCount( ) 统计记录数
3.Projections.avg() 统计平均值
4.Projections.min() 统计最小值
5.Projections.max() 统计最大值
6.Projections.count() 统计某一字段的非空记录数
7.Projections.sum() 统计某一字段的求和
8.Projections.projectionList() 实现一次查询调用多个聚合查询方法
范例:
==============================DetachedCriteria=============================
CriteriaSpecification-->Criteria-->DetachedCriteria
Criteria和DetachedCriteria均可使用Criteria与Projection设置条件查询。创建形式不同:
Criteria,Session进行创建
DetachedCriteria,创建无须Session
适用范围:
在Web层,程序员使用DetachedCriteria构造查询条件。然后将DetachedCriteria作为方法调用参数传递给业务成对象。
业务层对象获得DetachedCriteria后,可以在Session范围内直接构造Criteria进行查询。
因此,查询语句的构造完全被搬离到Web层实现,而业务查询与查询条件构造完全解耦。
方法:
createAlias()
createCriteria()
范例:
1.DetachedCriteria detachedCriteria = DetachedCriteria
.forClass(Emp.class, "e")
.createAlias("e.dept", "d")
.add(Restrictions.eq("d.deptName", "财务部"))
.add(Restrictions.ilike("e.empName", "a", MatchMode.ANYWHERE));
List<Emp> list = detachedCriteria.getExecutableCriteria(session).list();
2.DetachedCriteria avgSalary = DetachedCriteria.forClass(Emp.class, "e")
.setProjection(Property.forName("salary").avg());
List<Emp> list = session.createCriteria(Emp.class)
.add(Property.forName("salary").gt(avgSalary)).list();
======================================综合范例=======================================
1.entity包
a.Dept
1 package com.Elastic.HibernateDemo3.ivy.entity; 2 import java.io.Serializable; 3 import java.util.Set; 4 public class Dept implements Serializable { 5 private static final long serialVersionUID = 2261199233032137882L; 6 private Integer deptId; 7 private String deptName; 8 private String location; 9 10 //多对一:一个部门有多个员工 11 //set:唯一 12 private Set<Emp> emps; 13 14 public Set<Emp> getEmps() { 15 return emps; 16 } 17 public void setEmps(Set<Emp> emps) { 18 this.emps = emps; 19 } 20 21 public Integer getDeptId() { 22 return deptId; 23 } 24 public void setDeptId(Integer deptId) { 25 this.deptId = deptId; 26 } 27 public String getDeptName() { 28 return deptName; 29 } 30 public void setDeptName(String deptName) { 31 this.deptName = deptName; 32 } 33 public String getLocation() { 34 return location; 35 } 36 public void setLocation(String location) { 37 this.location = location; 38 } 39 }
b.Dept.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <class name="com.Elastic.HibernateDemo4.ivy.entity.Dept" table="dept"> 7 <!-- 主键 --> 8 <id name="deptId" column="deptid"> 9 <!-- 主键生成策略 --> 10 <generator class="increment"></generator> 11 </id> 12 <property name="deptName" column="deptname"></property> 13 <property name="location" column="location"></property> 14 15 <!-- 多个员工 --> 16 <set name="emps" cascade="all" inverse="true" order-by="empNo desc" lazy="extra"> 17 <key column="deptid"></key> 18 <one-to-many class="com.Elastic.HibernateDemo4.ivy.entity.Emp"/> 19 </set> 20 </class> 21 </hibernate-mapping>
a1.Emp
1 package com.Elastic.HibernateDemo3.ivy.entity; 2 import java.io.Serializable; 3 public class Emp implements Serializable { 4 private static final long serialVersionUID = -6182713107749938132L; 5 private Integer empNo; 6 private String empName; 7 private Integer deptId; 8 9 private Dept dept; 10 11 public Integer getDeptId() { 12 return deptId; 13 } 14 public void setDeptId(Integer deptId) { 15 this.deptId = deptId; 16 } 17 public Dept getDept() { 18 return dept; 19 } 20 public void setDept(Dept dept) { 21 this.dept = dept; 22 } 23 public Integer getEmpNo() { 24 return empNo; 25 } 26 public void setEmpNo(Integer empNo) { 27 this.empNo = empNo; 28 } 29 public String getEmpName() { 30 return empName; 31 } 32 public void setEmpName(String empName) { 33 this.empName = empName; 34 } 35 }
b1.Emp.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <class name="com.Elastic.HibernateDemo4.ivy.entity.Emp" table="emp"> 7 <!-- 主键 --> 8 <id name="empNo" column="empNo"> 9 <!-- 主键生成策略 --> 10 <generator class="increment"></generator> 11 </id> 12 <property name="empName" column="empName"></property> 13 <property name="deptId" column="deptId" insert="false" update="false"></property> 14 15 <!-- 多对一的关系(多个员工属于一个部门) --> 16 <many-to-one name="dept" class="com.Elastic.HibernateDemo4.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one> 17 </class> 18 19 <!-- 配置HQL命名查询 --> 20 <query name="findEmpByDeptName"> 21 <![CDATA[ 22 from Emp e where e.dept.deptName = :deptname and e.empName = :ename 23 ]]> 24 </query> 25 26 <!-- 配置原生的SQL语句 --> 27 <sql-query name="findEmp"> 28 <return alias="e" class="com.Elastic.HibernateDemo4.ivy.entity.Emp"></return> 29 select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname 30 </sql-query> 31 </hibernate-mapping>
2.hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE hibernate-configuration PUBLIC 4 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 5 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 6 <hibernate-configuration> 7 <session-factory> 8 <!-- 连接数据库 --> 9 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> 10 <property name="connection.username">root</property> 11 <property name="connection.password">root</property> 12 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 13 <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> 14 <property name="show_sql">true</property> 15 <property name="format_sql">true</property> 16 17 <!-- 数据库对应的实体类的映射文件路径 --> 18 <mapping resource="com/Elastic/HibernateDemo4/ivy/entity/Dept.hbm.xml"></mapping> 19 <mapping resource="com/Elastic/HibernateDemo4/ivy/entity/Emp.hbm.xml"></mapping> 20 21 </session-factory> 22 </hibernate-configuration>
3.util包
a.HibernateUtil
1 package com.Elastic.HibernateDemo4.ivy.util; 2 import org.hibernate.Session; 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 public final class HibernateUtil { 6 private static Configuration cfg = null; 7 private static SessionFactory sessionFactory = null; 8 9 //本地线程 10 public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 11 12 static{ 13 cfg = new Configuration().configure(); 14 sessionFactory = cfg.buildSessionFactory(); 15 } 16 17 public static Session getSession(){ 18 Session session = threadLocal.get(); 19 if (null == session || !session.isOpen()) { 20 session = sessionFactory.openSession(); 21 threadLocal.set(session); 22 } 23 return session; 24 } 25 }
4.test包
a.对象查询的基本操作
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 27 //查询在1楼的所有部门 28 criteria.add(Restrictions.eq("location", "1楼")); 29 30 //查询1楼的所有部门 31 criteria.add(Restrictions.like("location", "1楼")); 32 33 //查询含1的楼层的所有部门 34 criteria.add(Restrictions.like("location", "1", MatchMode.ANYWHERE)); 35 36 //查询部门编号为1或者位置在5楼的部门 37 criteria.add(Restrictions.or(Restrictions.eq("deptId", 1), Restrictions.eq("location", "5楼"))); 38 39 //查询部门编号为1或者4的部门 40 //in:第二个参数(字段值)数组或集合 41 criteria.add(Restrictions.in("deptId", new Integer[]{1, 4})); 42 43 //集合 44 List<Integer> params = new ArrayList<Integer>(); 45 params.add(1); 46 params.add(4); 47 criteria.add(Restrictions.in("deptId", params)); 48 49 //返回集合(若没条件,就返回所有的数据) 50 List<Dept> depts = criteria.list(); 51 for (Dept dept : depts) { 52 System.out.println("部门编号:" + dept.getDeptId() + ",部门名称:" + dept.getDeptName() + ",部门位置:" + dept.getLocation() + "\n"); 53 } 54 } 55 }
b.多条件查询
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 //查询在5楼且部门编号为1的部门 27 Map<String, Object> params = new HashMap<String, Object>(); 28 params.put("location", "5楼"); 29 params.put("deptId", 1); 30 for (String key : params.keySet()) { 31 criteria.add(Restrictions.eq(key, params.get(key))); 32 } 33 //返回集合(若没条件,就返回所有的数据) 34 List<Dept> depts = criteria.list(); 35 for (Dept dept : depts) { 36 System.out.println("部门编号:" + dept.getDeptId() + ",部门名称:" + dept.getDeptName() + ",部门位置:" + dept.getLocation() + "\n"); 37 } 38 } 39 }
c.排序
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 //按部门编号降序排列 27 criteria.addOrder(Order.desc("deptId")); 28 //按部门位置升序排列 29 criteria.addOrder(Order.asc("location")); 30 //中文排序??? 31 criteria.addOrder(Order.desc("deptName")); 32 //返回集合(若没条件,就返回所有的数据) 33 List<Dept> depts = criteria.list(); 34 for (Dept dept : depts) { 35 System.out.println("部门编号:" + dept.getDeptId() + ",部门名称:" + dept.getDeptName() + ",部门位置:" + dept.getLocation() + "\n"); 36 } 37 } 38 }
d.投影
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 //查询总条数 27 criteria.setProjection(Projections.rowCount()); 28 int total = Integer.parseInt(criteria.uniqueResult().toString()); 29 System.out.println(total); 30 System.out.println("记录数:" + criteria.list().iterator().next()); 31 32 //取消查询总条数 33 criteria.setProjection(null); 34 } 35 }
e.分页
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 criteria.setFirstResult(0); 27 criteria.setMaxResults(2); 28 29 //查询部门编号最大的部门信息 30 criteria.addOrder(Order.desc("deptId")); 31 criteria.setFirstResult(0); 32 criteria.setMaxResults(1); 33 Dept d = (Dept) criteria.uniqueResult(); 34 System.out.println("部门编号:" + d.getDeptId() + ",部门名称:" + d.getDeptName() + ",部门位置:" + d.getLocation() + "\n"); 35 } 36 }
f.关联
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 //查询黎明所在的部门 27 Criteria empCriteria = criteria.createAlias("emps", "emp"); 28 empCriteria.add(Restrictions.eq("emp.empName", "黎明")); 29 List<Dept> depts = empCriteria.list(); 30 for (Dept dept : depts) { 31 System.out.println("部门编号:" + dept.getDeptId() + ",部门名称:" + dept.getDeptName() + ",部门位置:" + dept.getLocation() + "\n"); 32 } 33 34 //只查询部门名称 35 //org.hibernate.criterion.Property 36 /*criteria.setProjection(Property.forName("deptName")); 37 List<String> names = criteria.list(); 38 for (String name : names) { 39 System.out.println(name); 40 }*/ 41 42 //只查询部门的名称和编号 43 /*criteria.setProjection(Projections.projectionList() 44 .add(Property.forName("deptName")) 45 .add(Property.forName("deptId"))); 46 List<Object[]> datas = criteria.list(); 47 for (Object[] objects : datas) { 48 System.out.println(objects[0].toString() + objects[1]); 49 }*/ 50 51 //统计部门编号的平均值 52 /*criteria.setProjection(Projections.avg("deptId")); 53 Object result = criteria.uniqueResult(); 54 System.out.println(result);*/ 55 } 56 }
g.DetachedCriteria查询
1 package com.Elastic.HibernateDemo4.ivy.test; 2 import java.util.ArrayList; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import java.util.Set; 7 import org.hibernate.Criteria; 8 import org.hibernate.FetchMode; 9 import org.hibernate.Session; 10 import org.hibernate.criterion.DetachedCriteria; 11 import org.hibernate.criterion.MatchMode; 12 import org.hibernate.criterion.Order; 13 import org.hibernate.criterion.Projection; 14 import org.hibernate.criterion.Projections; 15 import org.hibernate.criterion.Property; 16 import org.hibernate.criterion.Restrictions; 17 import org.hibernate.transform.ResultTransformer; 18 import com.Elastic.HibernateDemo4.ivy.entity.Dept; 19 import com.Elastic.HibernateDemo4.ivy.entity.Emp; 20 import com.Elastic.HibernateDemo4.ivy.util.HibernateUtil; 21 import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; 22 public class Test { 23 public static void main(String[] args) { 24 Session session = HibernateUtil.getSession(); 25 Criteria criteria = session.createCriteria(Dept.class); 26 //查询销售部的王五的所在部门的楼层 27 //方法1 28 DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Dept.class); 29 detachedCriteria.add(Restrictions.eq("deptName", "销售部")); 30 DetachedCriteria empDetachedCriteria = detachedCriteria.createCriteria("emps"); 31 empDetachedCriteria.add(Restrictions.eq("empName", "王五")); 32 Criteria deptCriteria = detachedCriteria.getExecutableCriteria(session); 33 List<Dept> depts = deptCriteria.list(); 34 for (Dept dept : depts) { 35 System.out.println(dept.getLocation()); 36 } 37 38 //方法2 39 criteria.setFetchMode("emps", FetchMode.JOIN); 40 List<Dept> list = criteria.list(); 41 for (Dept dept : list) { 42 System.out.println(dept.getDeptName()); 43 Set<Emp> emps = dept.getEmps(); 44 for (Emp emp : emps) { 45 System.out.println("\t" + emp.getEmpName()); 46 } 47 } 48 } 49 }
==============================注解===============================
Hibernate提供了Hibernate Annotations扩展包,使用注解完成映射
优势:
替换hbm.xml文件。利用注解后,可不用定义持久化类对应的*.hbm.xml文件。直接以注解方式写入在持久化类中实现
步骤:
1.添加jar包
2.使用注解配置持久化类以及对象关联关系
3.使用AnnotationConfiguration建立SessionFactory
4.在Hibernate配置文件(hibernate.cfg.xml)中声明持久化类
配置持久化类:
注解 含义和作用
@Entity 将一个类声明为一个持久化类
@Id 声明了持久化类的标识属性
@GeneratedValue 定义标识属性值的生成策略
@Table 为持久化类映射指定表
@Column 将属性映射到列(字段)
@Lob 将属性持久化为Blob或Clob类型
@Transient 将忽略这些属性,不用持久化到数据库
配置关联关系:
注解 含义和作用
@OneToOne 建立持久化类之间的一对一关联关系
@OneToMany 建立持久化类之间的一对多关联关系
@ManyToOne 建立持久化类之间的多对一关联关系
@ManyToMany 建立持久化类之间的多对多关联关系
配置命名查询--@NamedQuery
范例:
@Entity
@Table(name = "EMP")
@NamedQuery(name = "selectEmp", query = "from Emp where empName like :ename")
public class Emp implements java.io.Serializable {
//缺省其他代码
}
=================================同综合范例================================
1.entity包
a.Dept
1 package com.Elastic.HibernateDemo4.ivy.entity; 2 import java.io.Serializable; 3 import java.util.Set; 4 import javax.persistence.CascadeType; 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.FetchType; 8 import javax.persistence.Id; 9 import javax.persistence.OneToMany; 10 import javax.persistence.Table; 11 @Entity 12 @Table(name = "dept") 13 public class Dept implements Serializable { 14 15 @Id 16 /** 17 * nullable:是否为空 18 * nullable = false:非空 19 */ 20 @Column(name = "deptid", nullable = false) 21 private Integer deptId; 22 @Column(name = "deptname", nullable = false) 23 private String deptName; 24 25 private String location; 26 27 // 多对一: 一个部门有多个员工 28 /** 29 * @OneToMany-- 30 * mappedBy:指定“多”方的关联属性 31 * 在双向关联中,有且只有一端作为主体端,负责维护更新。 32 * 对于不需要维护这种关系的从表通过mappedBy声明,指向另一主体的关联性,相当于inverse="true" 33 * fetch:指定关联关系获取方式,即是否采用延迟加载 34 * cascade:指定级联操作 35 * 1.CascadeType.REMOVE:级联删除 36 * 2.CascadeType.PERSIST:级联新建 37 * 3.CascadeType.MERGE:级联更新 38 * 4.CascadeType.REFRESH:级联刷新 39 * 5.CascadeType.ALL:包含所有级联操作 40 * targetEntity:指定关联的实体类 41 */ 42 @OneToMany(cascade = CascadeType.ALL, targetEntity = Emp.class, mappedBy = "deptId", fetch = FetchType.LAZY) 43 private Set<Emp> emps; 44 45 public Integer getDeptId() { 46 return deptId; 47 } 48 49 public void setDeptId(Integer deptId) { 50 this.deptId = deptId; 51 } 52 53 public String getDeptName() { 54 return deptName; 55 } 56 57 public void setDeptName(String deptName) { 58 this.deptName = deptName; 59 } 60 61 public String getLocation() { 62 return location; 63 } 64 65 public void setLocation(String location) { 66 this.location = location; 67 } 68 69 public Set<Emp> getEmps() { 70 return emps; 71 } 72 73 public void setEmps(Set<Emp> emps) { 74 this.emps = emps; 75 } 76 77 }
b.Emp
1 package com.Elastic.HibernateDemo4.ivy.entity; 2 import java.io.Serializable; 3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.Id; 6 import javax.persistence.JoinColumn; 7 import javax.persistence.ManyToOne; 8 import javax.persistence.NamedNativeQuery; 9 import javax.persistence.NamedQuery; 10 import javax.persistence.Table; 11 @Entity 12 @Table(name = "emp") 13 14 //命名查询@NamedQuery:name属性:名字,query属性:hql语句 15 @NamedQuery(name="findHql",query="from Emp e where e.dept.deptName = :deptname and e.empName = :ename") 16 17 //原生命名查询@NamedNativeQuery:name属性:名字,query属性:sql语句 18 @NamedNativeQuery(name="findSql",query="select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname",resultClass=Emp.class) 19 public class Emp implements Serializable { 20 21 @Id 22 private Integer empNo; 23 private String empName; 24 25 /** 26 * insertable:是否可插入。 27 * false 不能;true 能 28 * updatable:是否可更新 29 * false 不能;true 能 30 * 31 * 这里的deptId是主表dept的主键,所以在从表中不能插入、更新deptId 32 */ 33 @Column(insertable = false, updatable = false) 34 private Integer deptId; 35 36 // 部门对象 37 /** 38 * @oneToMany的”多“方,通过@JoinColumn指定”多“方定义的外键字段 39 */ 40 @JoinColumn(name = "deptId") 41 42 //多个员工对应一个部门@ManyToOne 43 @ManyToOne(targetEntity = Dept.class) 44 private Dept dept; 45 46 public Integer getEmpNo() { 47 return empNo; 48 } 49 50 public void setEmpNo(Integer empNo) { 51 this.empNo = empNo; 52 } 53 54 public String getEmpName() { 55 return empName; 56 } 57 58 public void setEmpName(String empName) { 59 this.empName = empName; 60 } 61 62 public Integer getDeptId() { 63 return deptId; 64 } 65 66 public void setDeptId(Integer deptId) { 67 this.deptId = deptId; 68 } 69 70 public Dept getDept() { 71 return dept; 72 } 73 74 public void setDept(Dept dept) { 75 this.dept = dept; 76 } 77 78 }
2.hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE hibernate-configuration PUBLIC 4 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 5 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 6 7 <hibernate-configuration> 8 <session-factory> 9 <!-- 连接数据库 --> 10 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> 11 <property name="connection.username">root</property> 12 <property name="connection.password">root</property> 13 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 14 <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> 15 <property name="show_sql">true</property> 16 <property name="format_sql">true</property> 17 18 <!-- 注解 --> 19 <mapping class="com.Elastic.HibernateDemo4.ivy.entity.Dept"></mapping> 20 <mapping class="com.Elastic.HibernateDemo4.ivy.entity.Emp"></mapping> 21 22 </session-factory> 23 </hibernate-configuration>