Hibernate支持三种查询语言:HQL查询、Criteria查询和原生SQL查询
HQL(hibernate Query Language,hibernate查询语言)是一种面向对象查询语言,其中没有表和字段的概念,只有类、对象和属性的概念
语法:
form子句:form +全类名 / form + 类名(查询所有)
select子句:select dept.deptname from Dept
where子句:from dept where deptName='sales';
HQL执行语句
例子:form子句、select子句、where子句以及参数查询
建立实体类
public class Dept { private Integer deptno; private String dname; public Dept() { } public Dept(Integer deptno, String dname) { this.deptno = deptno; this.dname = dname; } public Integer getDeptno() { return deptno; } public void setDeptno(Integer deptno) { this.deptno = deptno; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; }}
测试方法
package cn;import cn.happy.entity.Dog;import cn.hib.entity.Dept;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Before;import org.junit.Test;import java.util.List;/** * Created by a on 2017/8/20. */public class Test924 { Configuration cfg; SessionFactory factory; Session session; Transaction tx; @Before public void beforeTest(){ //创建配置对象 cfg=new Configuration().configure(); //根据配置对象创建SessonFactory factory=cfg.buildSessionFactory(); //根据SessionFactory创建Session session=factory.getCurrentSession(); //session=factory.openSession(); //开启事务 tx=session.beginTransaction(); } @Test public void testlist(){ String hql="from Dept"; Query query=session.createQuery(hql); Listlist=query.list(); for (Dept dept : list){ System.out.println(dept.getDname()); } } @Test public void selectSomeColumnFromTable(){ String hql="select dept.deptno,dept.dname from Dept"; Query query=session.createQuery(hql); List