本文主要使用一些测试方法来讲解HQL的具体应用
采用一对多的关系映射举例,两个类Dept{did,dname,emps},Emp{dept,eid,ename}
Dept.hbm.xml中
[html]
<hibernate-mapping package="com.tarena.demo.po">
<class name="Dept" table="t_dept">
<id name="did" column="did">
<generator class="identity"></generator>
</id>
<property name="dname"></property>
<set name="emps" cascade="all" inverse="true">
<key column="did"></key>
<one-to-many class="Emp"/>
</set>
</class>
</hibernate-mapping>
Emp.hbm.xml中
[html]
<hibernate-mapping package="com.tarena.demo.po">
<class name="Emp" table="t_emp">
<id name="eid" column="eid">
<generator class="identity"></generator>
</id>
<property name="ename"></property>
<many-to-one name="dept" column="did" class="Dept"></many-to-one>
<query name="findEmpByEid">
<![CDATA[
from Emp where eid<?
]]>
</query>
</class>
</hibernate-mapping>
测试类:
[java]
public class TestHQL {
/**
* Hibernate生成关系模型
*/
@Test
public void test00DDL(){
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}
@Test
public void test01InitData(){
//10个部门,30个员工
Session session = HibernateUtils.getSession();
for(int i=1;i<=10;i++){
Dept dept = new Dept();
dept.setDname("部门"+i);
Set<Emp> emps = new HashSet<Emp>();
for(int j=1;j<=8;j++){
Emp emp = new Emp();
emp.setEname("员工_"+i+"_"+j);
emp.setDept(dept);
emps.add(emp);
}
dept.setEmps(emps);
session.save(dept);
session.clear();
}
session.beginTransaction().commit();
HibernateUtils.close(session);
}
/**
* 查询属性
* 查询一个属性,集合中的数据类型为String(对于dname属性),
* 如果对于did属性,则是Integer类型
*/
@Test
public void test02(){
Session session = HibernateUtils.getSession();
String hql = "select dname from Dept";
Query query = session.createQuery(hql);
List<String> dnames = query.list();
for (String dname : dnames) {
System.out.println(dname);
}
HibernateUtils.close(session);
}
/**
* 查询多个属性,集合中数据的类型为Object[]
*/
@Test
public void test03(){
Session session = HibernateUtils.getSession();
String hql = "select did,dname from Dept";
Query query = session.createQuery(hql);
List<Object[]> dnames = query.list();
for (Object[] o : dnames) {
System.out.println(o[0]+":"+o[1]);
}
HibernateUtils.close(session);
}
/**
* 查询多个属性,动态构建一个对象,Dept类必须要有new Dept(dname,did)构造器
* 和无参构造器
*/
@Test
public void test04(){
Session session = HibernateUtils.getSession();
String hql = "select new Dept(did,dname) from Dept";
Query query = session.createQuery(hql);
List<Dept> depts = query.list();
for(Dept dept:depts){
System.out.println(dept.getDname());
}
HibernateUtils.close(session);
}
/**