hibernate系列十六:分组查询,子查询,原生sql查询,命名查询

一  分组查询

HQL查询语句使用groupby子句进行分组查询,使用having子句筛选分组结果。下面通过示例说明。

案例1.  按性别分组,查询学生的平均年龄

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class GroupTest1 {
	public static void main(String[] args) {
		Session session=null;
		String hqlStr="select gender,avg(age) from StudentEntity group by gender";
		try {
			session=HiberUtil.getSession();
			Query qy=session.createQuery(hqlStr);
			List<Object[]> stuList=qy.list();
			Object[] theRow=null;
			for(int i=0;i<stuList.size();i++){
				theRow=stuList.get(i);
				System.out.println(theRow[0]+"\t"+theRow[1]);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}

案例二.   按照系名分组,查询每个系的学生的最高年龄,最低年龄,平均年龄,并且平均年龄要大于20岁

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class GroupJoinTest2 {
	public static void main(String[] args) {
		Session session=null;
		String hqlStr="SELECT d.departName,MAX(s.age),MIN(s.age),AVG(s.age) "
					+" FROM StudentEntity s INNER JOIN s.dept d"
					+" GROUP BY d.departName"
					+" having avg(s.age)>20";
		try {
			session=HiberUtil.getSession();
			Query qy=session.createQuery(hqlStr);
			List<Object[]> stuList=qy.list();
			Object[] theRow=null;
			for(int i=0;i<stuList.size();i++){
				theRow=stuList.get(i);
				System.out.println(theRow[0]+"\t"+theRow[1]+"\t"+theRow[2]+"\t"+theRow[3]);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}
二  子查询

案例1   查年龄高于平均年龄的学生

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class ChildQuery1 {
	public static void main(String[] args) {
		Session session=null;
		//查年龄高于平均年龄的学生
		String hqlStr="from StudentEntity s where s.age>(select avg(age) from StudentEntity)"; 
		try {
			session=HiberUtil.getSession();
			Query qy=session.createQuery(hqlStr);
			List<StudentEntity> stuList=qy.list();
			StudentEntity stu=null;
			for(int i=0;i<stuList.size();i++){
				stu=stuList.get(i);
				System.out.println(stu.getStuName()+"\t"+stu.getAge()+"\t"+stu.getGender());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}
案例2  所有学生年龄都大于21的系

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class ChildQuery2 {
	public static void main(String[] args) {
		Session session=null;
		//所有学生年龄都大于21的系
		String hqlStr="from DeptEntity d where 21<all(select s.age from d.stuList s) and d.stuList.size>0"; 
		try {
			session=HiberUtil.getSession();
			Query qy=session.createQuery(hqlStr);
			List<DeptEntity> deptList=qy.list();
			DeptEntity stu=null;
			for(int i=0;i<deptList.size();i++){
				stu=deptList.get(i);
				System.out.println(stu.getDepartName()+"\t"+stu.getAddress());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}

案例3   查学生的个数要大于3的系

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class ChildQuery3 {
	public static void main(String[] args) {
		Session session=null;
		//查学生的个数要大于3的系
		String hqlStr="from DeptEntity d where d.stuList.size>3"; 
		try {
			session=HiberUtil.getSession();
			Query qy=session.createQuery(hqlStr);
			List<DeptEntity> deptList=qy.list();
			DeptEntity stu=null;
			for(int i=0;i<deptList.size();i++){
				stu=deptList.get(i);
				System.out.println(stu.getDepartName()+"\t"+stu.getAddress());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}

三  原生sql查询

     使用HQL查询时,Hibernate会生成标准的SQL查询语句,适用于所有的数据库平台,因此HQL是跨数据库平台的。在实际开发中,有时很可能需要使用底层数据库的SQL特性,来生成一些特殊的查询语句。Hibernate提供了原生SQL的查询方式来支持这一需要。

案例1   

package com.obtk.test;

import java.text.SimpleDateFormat;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class SrcQueryTest1 {
	public static void main(String[] args) {
		Session session=null;
		String srcSql="select sysdate()";
		try {
			session=HiberUtil.getSession();
			Query qy=session.createSQLQuery(srcSql);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateStr=sdf.format(qy.uniqueResult());
			System.out.println(dateStr);
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}

案例2  

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class SrcQueryTest2 {
	public static void main(String[] args) {
		Session session=null;
		String hqlStr="SELECT table_name,create_time FROM information_schema.tables"
					+" WHERE table_schema='studentdb'";
		try {
			session=HiberUtil.getSession();
			Query qy=session.createSQLQuery(hqlStr);
			List<Object[]> stuList=qy.list();
			Object[] theRow=null;
			for(int i=0;i<stuList.size();i++){
				theRow=stuList.get(i);
				System.out.println(theRow[0]+"\t"+theRow[1]);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}


四  命名查询

    Hibernate支持在映射文件中定义字符串形式的查询语句,这样的查询语句称为命名查询语句。

===========================映射文件==============================

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.obtk.entitys">
    <class name="StudentEntity" table="student">
    	<cache usage="read-write" region="stu"/>
        <id name="stuId" type="java.lang.Integer">
            <column name="stuId" />
            <generator class="native"></generator>
        </id>
        <property name="stuName" type="java.lang.String">
            <column name="stuName" length="20" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="gender" length="2" />
        </property>
        <property name="age" type="integer">
            <column name="age" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="address" length="200" />
        </property>
        <many-to-one name="dept" class="DeptEntity"
        	column="deptIdd" lazy="proxy"></many-to-one>
    </class>
    <!-- 命名查询 -->
    <query name="getDept1">
    	<![CDATA[
    		from DeptEntity d where d.stuList.size>?
    	]]>
    </query>
    <!-- 原生sql命名查询 -->
    <sql-query name="srcNameQuery">
    	SELECT table_name,create_time FROM information_schema.tables
		WHERE table_schema='studentdb'
    </sql-query>
</hibernate-mapping>
案例1.  命名查询

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class NamingQuery1 {
	public static void main(String[] args) {
		Session session=null;
		//查学生的个数要大于3的系
		try {
			session=HiberUtil.getSession();
			Query qy=session.getNamedQuery("getDept1");
			qy.setParameter(0, 3);
			List<DeptEntity> deptList=qy.list();
			DeptEntity stu=null;
			for(int i=0;i<deptList.size();i++){
				stu=deptList.get(i);
				System.out.println(stu.getDepartName()+"\t"+stu.getAddress());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}
案例2   原生sql命名查询

package com.obtk.test;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.StudentEntity;
import com.obtk.utils.HiberUtil;

public class SrcNameQueryTest2 {
	public static void main(String[] args) {
		Session session=null;
		try {
			session=HiberUtil.getSession();
			Query qy=session.getNamedQuery("srcNameQuery");
			List<Object[]> stuList=qy.list();
			Object[] theRow=null;
			for(int i=0;i<stuList.size();i++){
				theRow=stuList.get(i);
				System.out.println(theRow[0]+"\t"+theRow[1]);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			HiberUtil.closeSession();
		}
	}
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值