Hibernate 原生SQL

hibernate 原生sql

如果你想使用数据库特定的功能如查询提示或 oracle 中的 connect 关键字的话,你可以使用原生 sql 数据库来表达查询。

hibernate 3.x 允许您为所有的创建,更新,删除,和加载操作指定手写 sql ,包括存储过程。

您的应用程序会在会话界面用 createsqlquery() 方法创建一个原生 sql 查询:

public sqlquery createsqlquery(string sqlstring) throws hibernateexception

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

 

标量查询

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

string sql = "select first_name, salary from employee";
sqlquery query = session.createsqlquery(sql);
query.setresulttransformer(criteria.alias_to_entity_map);
list results = query.list();

 

实体查询

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

string sql = "select * from employee";
sqlquery query = session.createsqlquery(sql);
query.addentity(employee.class);
list results = query.list();

 

指定 sql 查询

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

string sql = "select * from employee where id = :employee_id";
sqlquery query = session.createsqlquery(sql);
query.addentity(employee.class);
query.setparameter("employee_id", 10);
list results = query.list();

 

原生 sql 的例子

考虑下面的 pojo 类:

public class employee {
   private int id;
   private string firstname;
   private string lastname;   
   private int salary;  

   public employee() {}
   public employee(string fname, string lname, int salary) {
      this.firstname = fname;
      this.lastname = lname;
      this.salary = salary;
   }
   public int getid() {
      return id;
   }
   public void setid( int id ) {
      this.id = id;
   }
   public string getfirstname() {
      return firstname;
   }
   public void setfirstname( string first_name ) {
      this.firstname = first_name;
   }
   public string getlastname() {
      return lastname;
   }
   public void setlastname( string last_name ) {
      this.lastname = last_name;
   }
   public int getsalary() {
      return salary;
   }
   public void setsalary( int salary ) {
      this.salary = salary;
   }
}

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

create table employee (
   id int not null auto_increment,
   first_name varchar(20) default null,
   last_name  varchar(20) default null,
   salary     int  default null,
   primary key (id)
);

以下是映射文件:

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public
 "-//hibernate/hibernate mapping dtd//en"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="employee" table="employee">
      <meta attribute="class-description">
         this class contains the employee detail.
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstname" column="first_name" type="string"/>
      <property name="lastname" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

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

import java.util.*;

import org.hibernate.hibernateexception;
import org.hibernate.session;
import org.hibernate.transaction;
import org.hibernate.sessionfactory;
import org.hibernate.sqlquery;
import org.hibernate.criteria;
import org.hibernate.hibernate;
import org.hibernate.cfg.configuration;

public class manageemployee {
   private static sessionfactory factory;
   public static void main(string[] args) {
      try{
         factory = new configuration().configure().buildsessionfactory();
      }catch (throwable ex) {
         system.err.println("failed to create sessionfactory object." + ex);
         throw new exceptionininitializererror(ex);
      }
      manageemployee me = new manageemployee();

      /* add few employee records in database */
      integer empid1 = me.addemployee("zara", "ali", 2000);
      integer empid2 = me.addemployee("daisy", "das", 5000);
      integer empid3 = me.addemployee("john", "paul", 5000);
      integer empid4 = me.addemployee("mohd", "yasee", 3000);

      /* list down employees and their salary using scalar query */
      me.listemployeesscalar();

      /* list down complete employees information using entity query */
      me.listemployeesentity();
   }
   /* method to create an employee in the database */
   public integer addemployee(string fname, string lname, int salary){
      session session = factory.opensession();
      transaction tx = null;
      integer employeeid = null;
      try{
         tx = session.begintransaction();
         employee employee = new employee(fname, lname, salary);
         employeeid = (integer) session.save(employee);
         tx.commit();
      }catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace();
      }finally {
         session.close();
      }
      return employeeid;
   }

   /* method to  read all the employees using scalar query */
   public void listemployeesscalar( ){
      session session = factory.opensession();
      transaction tx = null;
      try{
         tx = session.begintransaction();
         string sql = "select first_name, salary from employee";
         sqlquery query = session.createsqlquery(sql);
         query.setresulttransformer(criteria.alias_to_entity_map);
         list data = query.list();

         for(object object : data)
         {
            map row = (map)object;
            system.out.print("first name: " + row.get("first_name"));
            system.out.println(", salary: " + row.get("salary"));
         }
         tx.commit();
      }catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace();
      }finally {
         session.close();
      }
   }

   /* method to  read all the employees using entity query */
   public void listemployeesentity( ){
      session session = factory.opensession();
      transaction tx = null;
      try{
         tx = session.begintransaction();
         string sql = "select * from employee";
         sqlquery query = session.createsqlquery(sql);
         query.addentity(employee.class);
         list employees = query.list();

         for (iterator iterator =
                           employees.iterator(); iterator.hasnext();){
            employee employee = (employee) iterator.next();
            system.out.print("first name: " + employee.getfirstname());
            system.out.print("  last name: " + employee.getlastname());
            system.out.println("  salary: " + employee.getsalary());
         }
         tx.commit();
      }catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace();
      }finally {
         session.close();
      }
   }
}

 

编译和执行

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

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

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

$java manageemployee
.......various log messages will display here........

first name: zara, salary: 2000
first name: daisy, salary: 5000
first name: john, salary: 5000
first name: mohd, salary: 3000
first name: zara  last name: ali  salary: 2000
first name: daisy  last name: das  salary: 5000
first name: john  last name: paul  salary: 5000
first name: mohd  last name: yasee  salary: 3000

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

mysql> select * from employee;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 26 | zara       | ali       |   2000 |
| 27 | daisy      | das       |   5000 |
| 28 | john       | paul      |   5000 |
| 29 | mohd       | yasee     |   3000 |
+----+------------+-----------+--------+
4 rows in set (0.00 sec)
mysql>

下一节:hibernate 缓存

hibernate 教程

相关文章