原生 SQL

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

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

    1. SQLQuery query = session.createSQLQuery(sql);
    2. query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    3. 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();

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

    这是编译并运行上述应用程序的步骤。确保你有适当的 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

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