原生 SQL

如果你想使用数据库特定的功能如查询提示或 Oracle 中的 CONNECT 关键字的话,你可以使用原生 SQL 数据库来表达查询。Hibernate 3.x 允许您为所有的创建,更新,删除,和加载操作指定手写 SQL ,包括存储过程。您的应用程序会在会话界面用 createSQLQuery() 方法创建一个原生 SQL 查询:

  1. public SQLQuery createSQLQuery(String sqlString) throws HibernateException

当你通过一个包含 SQL 查询的 createsqlquery() 方法的字符串时,你可以将 SQL 的结果与现有的 Hibernate 实体,一个连接,或一个标量结果分别使用 addEntity(), addJoin(), 和 addScalar() 方法进行关联。

标量查询

最基本的 SQL 查询是从一个或多个列表中获取一个标量(值)列表。以下是使用原生 SQL 进行获取标量的值的语法:

  1. String sql = "SELECT first_name, salary FROM EMPLOYEE";
  2. SQLQuery query = session.createSQLQuery(sql);
  3. query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
  4. List results = query.list();

实体查询

以上的查询都是关于返回标量值的查询,只是基础性地返回结果集中的“原始”值。以下是从原生 SQL 查询中通过 addEntity() 方法获取实体对象整体的语法:

  1. String sql = "SELECT * FROM EMPLOYEE";
  2. SQLQuery query = session.createSQLQuery(sql);
  3. query.addEntity(Employee.class);
  4. List results = query.list();

指定 SQL 查询

以下是从原生 SQL 查询中通过 addEntity() 方法和使用指定 SQL 查询来获取实体对象整体的语法:

  1. String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
  2. SQLQuery query = session.createSQLQuery(sql);
  3. query.addEntity(Employee.class);
  4. query.setParameter("employee_id", 10);
  5. List results = query.list();

原生 SQL 的例子

考虑下面的 POJO 类:

  1. public class Employee {
  2. private int id;
  3. private String firstName;
  4. private String lastName;
  5. private int salary;
  6. public Employee() {}
  7. public Employee(String fname, String lname, int salary) {
  8. this.firstName = fname;
  9. this.lastName = lname;
  10. this.salary = salary;
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public void setId( int id ) {
  16. this.id = id;
  17. }
  18. public String getFirstName() {
  19. return firstName;
  20. }
  21. public void setFirstName( String first_name ) {
  22. this.firstName = first_name;
  23. }
  24. public String getLastName() {
  25. return lastName;
  26. }
  27. public void setLastName( String last_name ) {
  28. this.lastName = last_name;
  29. }
  30. public int getSalary() {
  31. return salary;
  32. }
  33. public void setSalary( int salary ) {
  34. this.salary = salary;
  35. }
  36. }

让我们创建以下 EMPLOYEE 表来存储 Employee 对象:

  1. create table EMPLOYEE (
  2. id INT NOT NULL auto_increment,
  3. first_name VARCHAR(20) default NULL,
  4. last_name VARCHAR(20) default NULL,
  5. salary INT default NULL,
  6. PRIMARY KEY (id)
  7. );

以下是映射文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD//EN"
  4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="Employee" table="EMPLOYEE">
  7. <meta attribute="class-description">
  8. This class contains the employee detail.
  9. </meta>
  10. <id name="id" type="int" column="id">
  11. <generator class="native"/>
  12. </id>
  13. <property name="firstName" column="first_name" type="string"/>
  14. <property name="lastName" column="last_name" type="string"/>
  15. <property name="salary" column="salary" type="int"/>
  16. </class>
  17. </hibernate-mapping>

最后,我们将用 main() 方法创建应用程序类来运行应用程序,我们将使用原生 SQL 查询:

  1. import java.util.*;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.Transaction;
  5. import org.hibernate.SessionFactory;
  6. import org.hibernate.SQLQuery;
  7. import org.hibernate.Criteria;
  8. import org.hibernate.Hibernate;
  9. import org.hibernate.cfg.Configuration;
  10. public class ManageEmployee {
  11. private static SessionFactory factory;
  12. public static void main(String[] args) {
  13. try{
  14. factory = new Configuration().configure().buildSessionFactory();
  15. }catch (Throwable ex) {
  16. System.err.println("Failed to create sessionFactory object." + ex);
  17. throw new ExceptionInInitializerError(ex);
  18. }
  19. ManageEmployee ME = new ManageEmployee();
  20. /* Add few employee records in database */
  21. Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
  22. Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
  23. Integer empID3 = ME.addEmployee("John", "Paul", 5000);
  24. Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);
  25. /* List down employees and their salary using Scalar Query */
  26. ME.listEmployeesScalar();
  27. /* List down complete employees information using Entity Query */
  28. ME.listEmployeesEntity();
  29. }
  30. /* Method to CREATE an employee in the database */
  31. public Integer addEmployee(String fname, String lname, int salary){
  32. Session session = factory.openSession();
  33. Transaction tx = null;
  34. Integer employeeID = null;
  35. try{
  36. tx = session.beginTransaction();
  37. Employee employee = new Employee(fname, lname, salary);
  38. employeeID = (Integer) session.save(employee);
  39. tx.commit();
  40. }catch (HibernateException e) {
  41. if (tx!=null) tx.rollback();
  42. e.printStackTrace();
  43. }finally {
  44. session.close();
  45. }
  46. return employeeID;
  47. }
  48. /* Method to READ all the employees using Scalar Query */
  49. public void listEmployeesScalar( ){
  50. Session session = factory.openSession();
  51. Transaction tx = null;
  52. try{
  53. tx = session.beginTransaction();
  54. String sql = "SELECT first_name, salary FROM EMPLOYEE";
  55. SQLQuery query = session.createSQLQuery(sql);
  56. query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
  57. List data = query.list();
  58. for(Object object : data)
  59. {
  60. Map row = (Map)object;
  61. System.out.print("First Name: " + row.get("first_name"));
  62. System.out.println(", Salary: " + row.get("salary"));
  63. }
  64. tx.commit();
  65. }catch (HibernateException e) {
  66. if (tx!=null) tx.rollback();
  67. e.printStackTrace();
  68. }finally {
  69. session.close();
  70. }
  71. }
  72. /* Method to READ all the employees using Entity Query */
  73. public void listEmployeesEntity( ){
  74. Session session = factory.openSession();
  75. Transaction tx = null;
  76. try{
  77. tx = session.beginTransaction();
  78. String sql = "SELECT * FROM EMPLOYEE";
  79. SQLQuery query = session.createSQLQuery(sql);
  80. query.addEntity(Employee.class);
  81. List employees = query.list();
  82. for (Iterator iterator =
  83. employees.iterator(); iterator.hasNext();){
  84. Employee employee = (Employee) iterator.next();
  85. System.out.print("First Name: " + employee.getFirstName());
  86. System.out.print(" Last Name: " + employee.getLastName());
  87. System.out.println(" Salary: " + employee.getSalary());
  88. }
  89. tx.commit();
  90. }catch (HibernateException e) {
  91. if (tx!=null) tx.rollback();
  92. e.printStackTrace();
  93. }finally {
  94. session.close();
  95. }
  96. }
  97. }

编译和执行

这是编译并运行上述应用程序的步骤。确保你有适当的 PATH 和 CLASSPATH,然后执行编译程序。

  • 按照在配置一章讲述的方法创建 hibernate.cfg.xml 配置文件。
  • 如上述所示创建 employee.hbm.xml 映射文件。
  • 如上述所示创建 employee.java 源文件并编译。
  • 如上述所示创建 manageemployee.java 源文件并编译。
  • 执行 manageemployee 二进制代码运行程序。

你会得到下面的结果,并且记录将会在 EMPLOYEE 表创建。

  1. $java ManageEmployee
  2. .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
  3. First Name: Zara, Salary: 2000
  4. First Name: Daisy, Salary: 5000
  5. First Name: John, Salary: 5000
  6. First Name: Mohd, Salary: 3000
  7. First Name: Zara Last Name: Ali Salary: 2000
  8. First Name: Daisy Last Name: Das Salary: 5000
  9. First Name: John Last Name: Paul Salary: 5000
  10. First Name: Mohd Last Name: Yasee Salary: 3000

如果你检查你的 EMPLOYEE 表,它应该有以下记录:

  1. mysql> select * from EMPLOYEE;
  2. +----+------------+-----------+--------+
  3. | id | first_name | last_name | salary |
  4. +----+------------+-----------+--------+
  5. | 26 | Zara | Ali | 2000 |
  6. | 27 | Daisy | Das | 5000 |
  7. | 28 | John | Paul | 5000 |
  8. | 29 | Mohd | Yasee | 3000 |
  9. +----+------------+-----------+--------+
  10. 4 rows in set (0.00 sec)
  11. mysql>