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>