一、HQL 检索方式
以双向的一对多来测试 HQL 检索方式。以 Department 和 Employee 为例。
建表语句:
CREATE TABLE department ( dept_id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, dept_name VARCHAR(50) ); CREATE INDEX FK_8hf3vewo7w3v9doungcc51wwy ON department (dept_id);
CREATE TABLE employee ( emp_id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, emp_name VARCHAR(50), salary FLOAT, dept_id_fk INT(11), CONSTRAINT FK_miun1wlqp4ujpsgfshyfi7g9j FOREIGN KEY (dept_id_fk) REFERENCES department (dept_id) ); CREATE INDEX FK_miun1wlqp4ujpsgfshyfi7g9j ON employee (dept_id_fk);
对应的实体和 hbm 文件
public class Department { private Integer deptId; private String deptName; private Set<Employee> emps = new HashSet<>(); }
public class Employee { private Integer empId; private String empName; private Float salary; private Department dept; }
<hibernate-mapping> <class name="com.solverpeng.hql.Department" table="department" schema="hibernate"> <id name="deptId" column="dept_id"> <generator class="native"/> </id> <property name="deptName" column="dept_name"/> <set name="emps" inverse="true"> <key> <column name="dept_id_fk"/> </key> <one-to-many not-found="ignore" class="com.solverpeng.hql.Employee"/> </set> </class> </hibernate-mapping>