Hibernate框架简介⑤

版权声明:原创文章, 欢迎转载. https://blog.csdn.net/ip_JL/article/details/81591969

HQL查询

hql语句中没有*的写法:

测试代码:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate {
	
	@Test
	public void testAdd(){
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			for(int i = 0; i < 10; i++){
				User user = new User();
				user.setUname("任亮"+i);
				if(i%2 == 0){
					user.setGender(1);
				}else{
					user.setGender(2);
				}
				user.setSalary(1000+ i*100);
				user.setBirthday(new Date());
				session.save(user);
			}
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	@Test
	public void testQuery1(){
		Session session = HibernateUtils.getSession();
		
		try {
			//查询所有的user类的对象
			//String hql = "from User";//from 后面跟的是类名, 而非表名
			String hql = "select u from User u";//hql中没有*的写法
			
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//查询列表
			List<User> userList = query.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
}

单列查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate {
	
		
	/**
	 * 查询对象的属性
	 */
	@Test
	public void testQuery2(){
		Session session = HibernateUtils.getSession();
		
		try {
			//查询所有的user类的对象
			//String hql = "from User";
			String hql = "select u.uname from User u";//hql中没有*的写法
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//查询列表
			List<String> nameList = query.list();
			for(String name: nameList){
				System.out.println(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	
}

多个属性查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate {
	
	
	/**
	 * 查询对象的多个属性
	 */
	@Test
	public void testQuery3(){
		Session session = HibernateUtils.getSession();
		try {
			//查询所有的user类的对象
			//String hql = "from User";
			String hql = "select u.uname, u.gender from User u";//hql中没有*的写法
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//查询列表,多个属性的查询要使用Object[]来做接收
			List<Object[]> objArrList = query.list();
			for(Object[] objArr: objArrList){
				System.out.println("姓名:"+objArr[0]+"   性别:"+objArr[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	
}

分页查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate {
	
	
	
	/**
	 * 分页查询
	 */
	@Test
	public void testQuery4(){
		Session session = HibernateUtils.getSession();
		
		try {
			//查询所有的user类的对象
			//String hql = "from User";
			String hql = "select u from User u";//hql中没有*的写法
			
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//从前台传递过来的是页码PageNo,  startNum = (pageNo - 1)*pageSize
			//设置开始行号
			query.setFirstResult(5);
			//设置每页记录数pageSize
			query.setMaxResults(5);
			//查询列表
			List<User> userList = query.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	/**
	 * 分页查询
	 */
	@Test
	public void testQuery5(){
		Session session = HibernateUtils.getSession();
		try {
			//查询所有的user类的对象
			//String hql = "from User";
			String hql = "select u from User u";//hql中没有*的写法
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//从前台传递过来的是页码PageNo,  startNum = (pageNo - 1)*pageSize
			
			//查询列表
			List<User> userList = query.setFirstResult(5)
										.setMaxResults(5)
										.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
}

限定查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate1 {
	
	
	/**
	 * 限定查询
	 */
	@Test
	public void testQuery5(){
		Session session = HibernateUtils.getSession();
		try {
		
			String hql = "select u from User u where u.gender = ? and u.uname = ?";//hql中没有*的写法
			Query query = session.createQuery(hql);
			//设置第一个参数的值,和JDBC不同,预编译的索引从0开始
			query.setParameter(0, 2);
			query.setParameter(1, "任亮5");
			List<User> userList = query.list();
			for(User user : userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	/**
	 * 限定查询
	 */
	@Test
	public void testQuery6(){
		Session session = HibernateUtils.getSession();
		try {
			//传参的语法		:[自定义名称]
			String hql = "select u from User u where u.gender = :gender and u.uname = :uname";//hql中没有*的写法
			Query query = session.createQuery(hql);
			//给自定义的参数赋值
			query.setParameter("gender", 1);
			query.setParameter("uname", "任亮8");
			List<User> userList = query.list();
			for(User user : userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
}

统计查询:

package com.rl.hiber.test.hql;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Test;

import com.rl.hiber.model.EmpBean;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate2 {
	
	
	/**
	 * 统计查询
	 */
	@Test
	public void testQuery5(){
		Session session = HibernateUtils.getSession();
		try {
			//查询记录数
			//String hql = "select count(u.userId) from User u";
			//查询最大值
			//String hql = "select max(u.userId) from User u";
			//查询最小值
			//String hql = "select min(u.userId) from User u";
			//查询平均值
			//String hql = "select avg(u.userId) from User u";
			//统计求和
			String hql = "select sum(u.userId) from User u";
			Query query = session.createQuery(hql);
			//查询唯一的结果
			Object obj = query.uniqueResult();
			System.out.println(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	@Test
	public void testQuery6(){
		Session session = HibernateUtils.getSession();
		try {
			
			//统计求和
			String hql = "select avg(u.salary), u.gender from User u group by u.gender having avg(u.salary) > 1400";
			Query query = session.createQuery(hql);
			//查询唯一的结果
			List<Object[]> objArrList = query.list();
			for(Object[] objArr : objArrList){
				System.out.println("平均工资:" + objArr[0]+ "  性别:"+objArr[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
}

投影查询:

package com.rl.hiber.test.hql;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Test;

import com.rl.hiber.model.EmpBean;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate2 {

	/**
	 * 投影查询
	 */
	@Test
	public void testQuery7(){
		Session session = HibernateUtils.getSession();
		try {
			
			//我们可以创建一个业务Bean,在Bean提供有参数的构造器来接收sql返回的值,创建出对象语法 在select后面new com.rl.hiber.model.EmpBean(max(u.salary), u.gender)
			String hql = "select new com.rl.hiber.model.EmpBean(max(u.salary), u.gender) from User u group by u.gender having avg(u.salary) > 1400";
			Query query = session.createQuery(hql);
			//查询唯一的结果
			List<EmpBean> objArrList = query.list();
			for(EmpBean objArr : objArrList){
				System.out.println(objArr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
}

排序查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate4 {
	
	@Test
	public void testAdd(){
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		
		try {
			for(int i = 0; i < 10; i++){
				User user = new User();
				user.setUname("任亮"+i);
				if(i%2 == 0){
					user.setGender(1);
				}else{
					user.setGender(2);
				}
				user.setSalary(1000+ i*100);
				user.setBirthday(new Date());
				session.save(user);
			}
			
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
	
	
	/**
	 * 按着工资排序
	 */
	@Test
	public void testQuery1(){
		Session session = HibernateUtils.getSession();
		try {
			//查询所有的user类的对象
			//String hql = "from User";
			String hql = "select u from User u order by u.salary desc";//hql中没有*的写法
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//查询列表
			List<User> userList = query.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
		
}

模糊查询:

package com.rl.hiber.test.hql;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate4 {
	
	
	/**
	 * 模糊查询
	 */
	@Test
	public void testQuery2(){
		Session session = HibernateUtils.getSession();
		try {
			//String hql = "select u from User u where u.uname like '%亮%'";//hql中没有*的写法
			//模糊查询和sql中的语法一致
			String hql = "select u from User u where u.uname like '%亮_'";//hql中没有*的写法
			//根据hql语句创建查询对象
			Query query = session.createQuery(hql);
			//查询列表
			List<User> userList = query.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}	
}

提取查询hql查询语句到配置文件中:

User.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
package:指定当前映射文件的实体类model所在的包
 -->
<hibernate-mapping package="com.rl.hiber.model">
	<!-- 
		lazy:当前类是否使用延迟加载,默认是true使用,false不使用
	 -->
	<class name="User" table="t_user">
		<!-- id
			是主键映射配置
		 -->
		<id name="userId" column="user_id">
			<!-- 
				generator:主键的映射策略
			 -->
			<generator class="native"></generator>
		</id>
		<property name="uname"></property>
		<property name="salary"></property>
		<property name="gender"></property>
		<property name="birthday"></property>
	</class>
	<!-- 
		query:定义hql语句
		name:查询的名字,唯一
	 -->
	<query name="getUserAll">
		<![CDATA[
			from User u where u.salary > :salary
		]]>
	</query>
</hibernate-mapping>

测试代码:

package com.rl.hiber.test.hql;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Test;

import com.rl.hiber.model.User;
import com.rl.hiber.utils.HibernateUtils;


public class TestHibernate5 {
	/**
	 * 限定查询
	 */
	@Test
	public void testQuery2(){
		Session session = HibernateUtils.getSession();
		try {
			//从映射文件中获得hql语句创建query对象
			Query query = session.getNamedQuery("getUserAll");
			query.setParameter("salary", 1500);
			//查询列表
			List<User> userList = query.list();
			for(User user: userList){
				System.out.println(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtils.closeResource(session);
		}
	}
}

 

阅读更多

没有更多推荐了,返回首页