Hibernate独家查询语言,面向对象的查询语言——HQL

详细的搭建步骤在这里:点击打开链接

在这我就直接上测试代码:

package cn.liangce.hql;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import cn.liangce.domain.Customer;
import cn.liangce.utils.HibernateUtils;
public class Demo {
	@Test
	//基本查询
	public void test1(){
		//1.获得session
		Session session = HibernateUtils.openSession();
		//2.控制事务
		Transaction ts = session.beginTransaction();
		//3,执行操作
		//1>书写sql语句
		String hql="from Customer";//查询所有Customer对象
		//2>.根据hql语句创建查询对象
		Query query = session.createQuery(hql);
		//3>.根据查询对象获取查询结果
		List list = query.list();//返回查询结果
		//query.uniqueResult() 返回唯一查询结果
		System.out.println(list);
		//4.提交事务,关闭资源
		ts.commit();
		session.close();
	}
	@Test
	//条件查询,笔记本查询多了占位符的处理
	public void test2(){
		//1.获得session
		Session session=HibernateUtils.openSession();
		//2.控制事务
		Transaction ts = session.beginTransaction();
		//3.执行操作
		//书写hql语句
		String hql="from Customer where cust_id=1";
		//获得查询对象
		Query query = session.createQuery(hql);
		Customer customer = (Customer) query.uniqueResult();
		System.out.println(customer);
		ts.commit();
		session.close();
	}
	@Test
	//条件查询,问号占位符的处理
	public void test3(){
		//1.获得session
		Session session = HibernateUtils.openSession();
		//2.控制事务
		Transaction ts = session.beginTransaction();
		//3.执行操作
		//书写hql
		String hql="from Customer where cust_id=?";
		//命名占位符
		//String hql = " from Customer where cust_id = :cust_id ";
		//获得查询对象
		Query query = session.createQuery(hql);
		//设置参数
		query.setParameter(0, 1l);
		//query.setParameter("cust_id", 1l);设置命名占位符
		//根据查询对象获得结果
		Customer customer = (Customer) query.uniqueResult();
		System.out.println(customer);
		//4.提交事务,关闭资源
		ts.commit();
		session.close();
	}
	@Test
	//分页查询
	public void test4(){
		//1.获得session
		Session session = HibernateUtils.openSession();
		//2.开启事务
		Transaction ts = session.beginTransaction();
		//3.执行操作
		//书写hql
		String hql="from Customer";//查询所有对象
		//获取查询对象
		Query query = session.createQuery(hql);
		//设置分页信息
		query.setFirstResult(0);
		query.setMaxResults(3);
		//根据对象获取查询结果
		List list = query.list();
		System.out.println(list);
		//4.提交事务,关闭资源
		ts.commit();
		session.close();
	}
}


你可能感兴趣的:(hibernate)