快捷搜索:

Hibernate HQL 级联注意事项<BR>1.1<span style="font: 7

Hibernate级联查询(HQL)

拿雇员(Employee)与部门(Department)来举例子阐明

1.1数据库模型

1.1.1Employee表

DROP TABLE IF EXISTS employee;

CREATE TABLE employee (

id int(11) NOT NULL auto_increment,

empname varchar(255) default NULL,

empage int(11) default NULL,

context varchar(255) default NULL,

deptid int(11) default NULL,

PRIMARY KEY (id),

KEY FK4722E6AEAD9148B6 (deptid)

) ENGINE=InnoDB DEFAULT CHARSET=gbk;

1.1.2Department表

DROP TABLE IF EXISTS department;

CREATE TABLE department (

id int(11) NOT NULL auto_increment,

deptname varchar(255) default NULL,

PRIMARY KEY (id)

) ENGINE=InnoDB DEFAULT CHARSET=gbk;

1.2Java类

publicclass Employee

{

private Integer id;

private String empname;

private Integer empage;

private String context;

private Integer deptid;

private Department department=new Department();

//此处省略set()、get()措施

}

publicclass Department

{

private Integer id;

private String deptname;

private SetEmployee> employeeSet=new HashSetEmployee>();

//此处省略set()、get()措施

}

1.3映射文件

hibernate-mapping package="com.dl.bean">

class name="Employee" table="employee">

id name="id" >

generator class="native"/>

id>

property name="empname"/>

property name="empage"/>

property name="context" />

property name="deptid" insert="false" update="false"/>

many-to-one name="department" column="deptid" cascade="all" class="Department" />

class>

hibernate-mapping>

hibernate-mapping package="com.dl.bean">

class name="Department" table="department">

id name="id" >

generator class="native"/>

id>

property name="deptname" />

set name="employeeSet">

key column="deptid">key>

one-to-many class="Employee"/>

set>

class>

hibernate-mapping>

1.4在写Hibernate级联查询的HQL语句时,与传统的JDBC要领有着本色的差别

1.4.1JDBC级联写法

SELECT * FROM employee INNER JOIN department ON employee.deptid= department.id

1.4.2HQL级联写法

select

employee.id,

employee.empname,

employee.empage,

employee.context,

employee.department.deptname

from

Employee employee

inner join employee.department (此处与前文中Employee类中的属性名同等)

order by employee.id desc

留意血色字体部分,在传统的SQL语句中inner join后面跟级联的表,但在HQL中inner join后面跟能反应出级联关系的字段属性(与pojo中的名字必须高度维持同等),当存在级联时,Hibernate查询结果为一工具数组,其数组的长度取决于select与from之间字段的个数。

1.5留意阐发下面三条语句看有什么不合

SQLQuery要领

sqlquery=session.createSQLQuery("select employee.id,employee.empname,employee.empage,employee.context,department.deptname from employee inner join department on employee.deptid=department.id");

Query要领:

session.createQuery("select employee.id,employee.empname,employee.empage,employee.context,employee.department.deptname from Employee employee inner join employee.department order by employee.id desc");

Query要领:

Query query=session.createQuery("select employee.empname, employee.department from Employee as employee order by employee.id desc");

您可能还会对下面的文章感兴趣: