Hibernate
Posted Ivyvivid
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 以上是关于Hibernate的主要内容,如果未能解决你的问题,请参考以下文章使用反射在外部JAR / CLASS上调用包含Hibernate事务的方法(Java EE)
Hibernate CriteriaQuery where - ManyToOne 字段
Hibernate + MySQL:如何为数据库和表设置编码 utf-8
hibernate在使用getCurrentSession时提示no session found for current thread