hibernate 原生sql
如果你想使用數(shù)據(jù)庫特定的功能如查詢提示或 oracle 中的 connect 關(guān)鍵字的話,你可以使用原生 sql 數(shù)據(jù)庫來表達(dá)查詢。
hibernate 3.x 允許您為所有的創(chuàng)建,更新,刪除,和加載操作指定手寫 sql ,包括存儲(chǔ)過程。
您的應(yīng)用程序會(huì)在會(huì)話界面用 createsqlquery()
方法創(chuàng)建一個(gè)原生 sql 查詢:
public sqlquery createsqlquery(string sqlstring) throws hibernateexception
當(dāng)你通過一個(gè)包含 sql 查詢的 createsqlquery() 方法的字符串時(shí),你可以將 sql 的結(jié)果與現(xiàn)有的 hibernate 實(shí)體,一個(gè)連接,或一個(gè)標(biāo)量結(jié)果分別使用 addentity(), addjoin(), 和 addscalar() 方法進(jìn)行關(guān)聯(lián)。
標(biāo)量查詢
最基本的 sql 查詢是從一個(gè)或多個(gè)列表中獲取一個(gè)標(biāo)量(值)列表。以下是使用原生 sql 進(jìn)行獲取標(biāo)量的值的語法:
string sql = "select first_name, salary from employee"; sqlquery query = session.createsqlquery(sql); query.setresulttransformer(criteria.alias_to_entity_map); list results = query.list();
實(shí)體查詢
以上的查詢都是關(guān)于返回標(biāo)量值的查詢,只是基礎(chǔ)性地返回結(jié)果集中的“原始”值。以下是從原生 sql 查詢中通過 addentity()
方法獲取實(shí)體對(duì)象整體的語法:
string sql = "select * from employee"; sqlquery query = session.createsqlquery(sql); query.addentity(employee.class); list results = query.list();
指定 sql 查詢
以下是從原生 sql 查詢中通過 addentity()
方法和使用指定 sql 查詢來獲取實(shí)體對(duì)象整體的語法:
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; } }
讓我們創(chuàng)建以下 employee 表來存儲(chǔ) employee 對(duì)象:
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() 方法創(chuàng)建應(yīng)用程序類來運(yùn)行應(yīng)用程序,我們將使用原生 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(); } } }
編譯和執(zhí)行
這是編譯并運(yùn)行上述應(yīng)用程序的步驟。確保你有適當(dāng)?shù)?path 和 classpath,然后執(zhí)行編譯程序。
- 按照在配置一章講述的方法創(chuàng)建
hibernate.cfg.xml
配置文件。 - 如上述所示創(chuàng)建
employee.hbm.xml
映射文件。 - 如上述所示創(chuàng)建
employee.java
源文件并編譯。 - 如上述所示創(chuàng)建
manageemployee.java
源文件并編譯。 - 執(zhí)行 manageemployee 二進(jìn)制代碼運(yùn)行程序。
你會(huì)得到下面的結(jié)果,并且記錄將會(huì)在 employee 表創(chuàng)建。
$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 表,它應(yīng)該有以下記錄:
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>
- JDBC 教程
- JDBC 驅(qū)動(dòng)類型
- JDBC 連接數(shù)據(jù)庫范例
- JDBC 連接數(shù)據(jù)庫步驟
- JDBC Statement, PreparedStatement 和 CallableStatement
- JDBC ResultSet 結(jié)果集
- JDBC Resultset 結(jié)果集范例
- JDBC 事務(wù)保存點(diǎn)范例
- Scala 教程
- Scala 簡介
- Scala 類和對(duì)象
- Scala 文件 I/O
- Spring 教程
- Spring 模塊
- Spring 依賴注入
- Spring 自動(dòng)裝配
- Spring MVC教程
- Spring MVC表單標(biāo)簽庫
- Spring security