Hibernate 调用SQL Server2008的存储过程(有参无参两种情况)和SQL语句

Hibernate 中同样可以调用存储过程,或SQL语句,下面列举如下;

一,创建相关表

  1. if OBJECT_ID(N'Book'is not null  
  2. goto showData  
  3.   
  4. --//create table BOOKS  
  5. --//----------Start create table----------  
  6. create table Book(  
  7. [bID] int identity(1,1) not null,  
  8. [bName] varchar(100) null,  
  9. [bCategory] int null,  
  10. [bDescriptioin] varchar(250) null,  
  11. [bAddTime] datetime null default getdate(),  
  12. [bMark] varchar(250) null,  
  13. primary key([bID])  
  14. )  

二,创建相应存储过程
  1. use TESTDB01  
  2. GO  
  3.   
  4. ----------------------------------  
  5. -- getAllBook()  
  6. ----------------------------------  
  7. if exists(select 1 from sysobjects where xtype=N'P' and name=N'getAllBook')  
  8. drop procedure getAllBook  
  9.   
  10. go  
  11. create procedure getAllBook  
  12. as   
  13. begin  
  14. select * from Books  
  15. end  
  16. go  
  17.   
  18. --TEST  
  19. exec getAllBook  
  20.   
  21. ----------------------------------  
  22. -- getBookByCategoryName()  
  23. ----------------------------------  
  24. if exists(select 1 from sysobjects where xtype=N'P' and name=N'getBookByCategoryName')  
  25. drop procedure getBookByCategoryName  
  26.   
  27. go  
  28. create procedure getBookByCategoryName  
  29. @category int,  
  30. @bookName varchar(50)  
  31. as  
  32. begin  
  33. declare @cid int  
  34. declare @findName varchar(50)  
  35. set @cid = @category  
  36. set @findName = @bookName  
  37. if(0 = @cid)  
  38.     select * from Books where charIndex(@findName,bName) > 0  
  39. else  
  40.     select * from Books where bCategory = @cid and charIndex(@findName,bName) > 0  
  41. end  
  42. go  
  43.   
  44. --TEST  
  45. exec getBookByCategoryName 0,'基础'  

三,Hibernate中的表映射XML文件(Book.hbm.xml)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <hibernate-mapping>  
  5.  <class catalog="TESTDB01" name="com.test.models.Book" schema="dbo" table="Book">  
  6.   <id name="bid" type="integer">  
  7.    <column name="bID"/>  
  8.    <generator class="native"/>  
  9.   </id>  
  10.   <property generated="never" lazy="false" name="bname" type="string">  
  11.    <column length="100" name="bName"/>  
  12.   </property>  
  13.   <property generated="never" lazy="false" name="bcategory" type="integer">  
  14.    <column name="bCategory"/>  
  15.   </property>  
  16.   <property generated="never" lazy="false" name="bdescriptioin" type="string">  
  17.    <column length="250" name="bDescriptioin"/>  
  18.   </property>  
  19.   <property generated="never" lazy="false" name="baddTime" type="timestamp">  
  20.    <column length="23" name="bAddTime"/>   
  21.   </property>  
  22.   <property generated="never" lazy="false" name="bmark" type="string">  
  23.    <column length="250" name="bMark"/>  
  24.   </property>  
  25.  </class>  
  26.   
  27.  <sql-query callable="true" name="getAllBook">  
  28.  {call getAllBook()}  
  29.  <!-- 此处也可以放SQL语句  -->  
  30.  <return alias="book" class="com.test.models.Book" entity-name="com.test.models.Book" >  
  31.    <!-- entity-name=""   
  32.    其中,alias属性可以符合标志符名称即可,无特别要求,class和entity-name指向相同,或只能二选一,因它们两都是指定返回对象类型 -->  
  33.    <return-property column="bID" name="bid"/>  
  34.    <return-property column="bName" name="bname"/>  
  35.    <return-property column="bCategory" name="bcategory"/>  
  36.    <return-property column="bDescriptioin" name="bdescriptioin"/>  
  37.    <return-property column="bAddTime" name="baddTime"/>  
  38.    <return-property column="bMark" name="bmark"/>  
  39.   </return>  
  40.  </sql-query>  
  41.  <sql-query callable="true" name="getBookByCategoryName">  
  42.  {call getBookByCategoryName(?,?)}  
  43.  <return  alias="book" class="com.test.models.Book">  
  44.     <return-property column="bID" name="bid"/>  
  45.     <return-property column="bName" name="bname"/>  
  46.     <return-property column="bCategory" name="bcategory"/>  
  47.     <return-property column="bDescriptioin" name="bdescriptioin"/>  
  48.     <return-property column="bAddTime" name="baddTime"/>  
  49.     <return-property column="bMark" name="bmark"/>  
  50.  </return>  
  51.  </sql-query>  
  52. </hibernate-mapping>  

四,页面或action中通过Hibernate调用存储过程

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ page language="java" import="com.test.hbm.HibernateSessionFactory"%>  
  3. <%@ page language="java" import="org.hibernate.SessionFactory"%>  
  4. <%@ page language="java" import="org.hibernate.Session"%>  
  5. <%@ page language="java" import="com.test.models.Book"%>  
  6. <%@ page language="java" import="com.test.common.Funs"%>  
  7. <%@ page language="java" import="org.hibernate.Query,org.hibernate.SQLQuery"%>  
  8. <%@page import="java.sql.ResultSet,java.sql.Connection,java.sql.CallableStatement"%>  
  9. <%@page import="org.hibernate.Hibernate"%>  
  10. <%  
  11. String path = request.getContextPath();  
  12. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  13. %>  
  14. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  15. <html>  
  16. <head>  
  17. <base href="<%=basePath%>">     
  18. <title>Hibernate call ms sql server 2008 procedure</title>     
  19. <meta http-equiv="pragma" content="no-cache">  
  20. <meta http-equiv="cache-control" content="no-cache">  
  21. <meta http-equiv="expires" content="0">      
  22. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  23. <meta http-equiv="description" content="This is my page">  
  24. <link rel="stylesheet" type="text/css" href="css/css01.css">  
  25. </head>    
  26. <body>  
  27. <p>  
  28. Hibernate call ms sql server 2008 SQL/Procedure [option with parameters]<br>  
  29. Hibernate 调用MS SQL Server2008的SQL语句或存储过程,有参无参两种情况  
  30. </p>  
  31.   
  32. <p><b>一,通过createQuery调用存储过程</b></p>    
  33. <%   
  34. //SessionFactory sf = HibernateSessionFactory.getSessionFactory();  
  35. //HibernateSessionFactory.rebuildSessionFactory();  
  36. //out.print("<br><br>hs object : " + hs.toString());  
  37. Session hs = HibernateSessionFactory.getSession();  
  38. out.print("<br>QueryString [无参] : " + hs.getNamedQuery("getAllBook").getQueryString());  
  39. List list = hs.getNamedQuery("getAllBook").list();  
  40. if(list.isEmpty()){  
  41.     out.print("<br><br>---------No data list---------");  
  42. }else{  
  43.     out.print("<br><br>");  
  44.     Iterator it = list.iterator();  
  45.     out.print("<table>");  
  46.     out.print("<tr bgColor=\"#cdcdcd\">");  
  47.     out.print("<td>ID</td>");   
  48.     out.print("<td>BookName</td>");   
  49.     out.print("<td>categoryID</td>");   
  50.     out.print("<td>Description</td>");   
  51.     out.print("<td>addTime</td>");   
  52.     out.print("<td>mark</td>");   
  53.     out.print("</tr>");  
  54.     while(it.hasNext()){  
  55.         Book book = (Book)it.next();  
  56.         out.print("<tr>");  
  57.         out.print("<td>" + book.getBid() + "</td>");  
  58.         //out.print("<td>" + Funs.str2UTF8(book.getBname()) + "</td>");  
  59.         out.print("<td>" + book.getBname() + "</td>");  
  60.         out.print("<td>" + book.getBcategory() + "</td>");  
  61.         out.print("<td>" + book.getBdescriptioin() + "</td>");  
  62.         out.print("<td>" + book.getBaddTime() + "</td>");  
  63.         out.print("<td>" + book.getBmark() + "</td>");  
  64.         out.print("</tr>");  
  65.     }  
  66.     out.print("</table>");  
  67. }  
  68. %>  
  69. <hr size="1" color="#999999">  
  70. <%    
  71. out.print("<br><br>QueryString [有参] : " + hs.getNamedQuery("getBookByCategoryName").getQueryString());  
  72. hs = HibernateSessionFactory.getSession();  
  73. Query query = hs.getNamedQuery("getBookByCategoryName");  
  74. query.setInteger(0,1); //Hibernate的参数设置下标从 0 开始  
  75. query.setString(1,"java");  
  76. list = query.list();  
  77. if(list.isEmpty()){  
  78.     out.print("<br><br>---------No data list---------");   
  79. }else{  
  80.     out.print("<br><br>");  
  81.     Iterator it = list.iterator();  
  82.     out.print("<table>");  
  83.     out.print("<tr bgColor=\"#cdcdcd\">");  
  84.     out.print("<td>ID</td>");  
  85.     out.print("<td>BookName</td>");  
  86.     out.print("<td>categoryID</td>");  
  87.     out.print("<td>Description</td>");  
  88.     out.print("<td>addTime</td>");  
  89.     out.print("<td>mark</td>");  
  90.     out.print("</tr>");  
  91.     while(it.hasNext()){  
  92.         Book book = (Book)it.next();  
  93.         out.print("<tr>");  
  94.         out.print("<td>" + book.getBid() + "</td>");  
  95.         //out.print("<td>" + Funs.str2UTF8(book.getBname()) + "</td>");  
  96.         out.print("<td>" + book.getBname() + "</td>");  
  97.         out.print("<td>" + book.getBcategory() + "</td>");  
  98.         out.print("<td>" + book.getBdescriptioin() + "</td>");  
  99.         out.print("<td>" + book.getBaddTime() + "</td>");  
  100.         out.print("<td>" + book.getBmark() + "</td>");  
  101.         out.print("</tr>");  
  102.     }   
  103.     out.print("</table>");  
  104. }  
  105. %>  
  106. <br>  
  107.   
  108. <hr size="2" color="blue">  
  109. <p><b>二,通过createSQLQuery调用存储过程</b></p>  
  110. <%   
  111. out.print("<br>QueryString [无参] : " + hs.getNamedQuery("getAllBook").getQueryString());  
  112. SQLQuery query3=hs.createSQLQuery("{call getAllBook()}");  
  113. query3.addEntity(Book.class);  
  114.   
  115. //上面两行等同于下面一行,把查询的结果绑定到对应的实体类,查询结果和实体类已经在hibernate的XML完成映射[字段名和实体属性名的映射]  
  116. //SQLQuery query3=hs.createSQLQuery("{call getAllBook()}").addEntity(Books.class);  
  117.   
  118. list = query3.list();  
  119. if(list.isEmpty()){  
  120.     out.print("<br><br>---------No data list---------");  
  121. }else{  
  122.     out.print("<br><br>");  
  123.     Iterator it = list.iterator();  
  124.     out.print("<table>");  
  125.     out.print("<tr bgColor=\"#cdcdcd\">");  
  126.     out.print("<td>ID</td>");  
  127.     out.print("<td>BookName</td>");  
  128.     out.print("<td>categoryID</td>");  
  129.     out.print("<td>Description</td>");  
  130.     out.print("<td>addTime</td>");  
  131.     out.print("<td>mark</td>");  
  132.     out.print("</tr>");  
  133.     while(it.hasNext()){  
  134.         Book book = (Book)it.next();  
  135.         out.print("<tr>");  
  136.         out.print("<td>" + book.getBid() + "</td>");  
  137.         out.print("<td>" + book.getBname() + "</td>");  
  138.         out.print("<td>" + book.getBcategory() + "</td>");  
  139.         out.print("<td>" + book.getBdescriptioin() + "</td>");  
  140.         out.print("<td>" + book.getBaddTime() + "</td>");  
  141.         out.print("<td>" + book.getBmark() + "</td>");  
  142.         out.print("</tr>");  
  143.     }  
  144.     out.print("</table>");  
  145. }  
  146. %>  
  147. <hr size="1" color="#999999">  
  148. <%   
  149. out.print("<br><br>QueryString [有参] : " + hs.getNamedQuery("getBookByCategoryName").getQueryString());  
  150. hs = HibernateSessionFactory.getSession();  
  151. SQLQuery query4 = hs.createSQLQuery("{call getBookByCategoryName(?,?)}").addEntity(Book.class);  
  152. query4.setInteger(0,1);  
  153. query4.setString(1,"java");  
  154. list = query4.list();  
  155. if(list.isEmpty()){  
  156.     out.print("<br><br>---------No data list---------");   
  157. }else{  
  158.     out.print("<br><br>");  
  159.     Iterator it = list.iterator();  
  160.     out.print("<table>");  
  161.     out.print("<tr bgColor=\"#cdcdcd\">");  
  162.     out.print("<td>ID</td>");  
  163.     out.print("<td>BookName</td>");  
  164.     out.print("<td>categoryID</td>");  
  165.     out.print("<td>Description</td>");  
  166.     out.print("<td>addTime</td>");  
  167.     out.print("<td>mark</td>");  
  168.     out.print("</tr>");  
  169.     while(it.hasNext()){  
  170.         Book book = (Book)it.next();  
  171.         out.print("<tr>");  
  172.         out.print("<td>" + book.getBid() + "</td>");  
  173.         //out.print("<td>" + Funs.str2UTF8(book.getBname()) + "</td>");  
  174.         out.print("<td>" + book.getBname() + "</td>");  
  175.         out.print("<td>" + book.getBcategory() + "</td>");  
  176.         out.print("<td>" + book.getBdescriptioin() + "</td>");  
  177.         out.print("<td>" + book.getBaddTime() + "</td>");  
  178.         out.print("<td>" + book.getBmark() + "</td>");  
  179.         out.print("</tr>");  
  180.     }   
  181.     out.print("</table>");  
  182. }  
  183. %>  
  184. <hr size="2" color="blue">  
  185. <p><b>三,通过JDBC方式调用存储过程</b></p>  
  186.   
  187. <%   
  188. hs =HibernateSessionFactory.getSession();     
  189. Connection conn = hs.connection();     
  190. ResultSet rs =null;    
  191. CallableStatement cs = conn.prepareCall("{Call getAllBook()}");    
  192. rs = cs.executeQuery();    
  193. out.print("<br>调用无参数的存储过程:");  
  194. out.print("<table>");  
  195. out.print("<tr bgColor=\"#cdcdcd\">");  
  196. out.print("<td>ID</td>");  
  197. out.print("<td>BookName</td>");  
  198. out.print("<td>categoryID</td>");  
  199. out.print("<td>Description</td>");  
  200. out.print("<td>addTime</td>");  
  201. out.print("<td>mark</td>");  
  202. out.print("</tr>");  
  203. while(rs.next()){  
  204.         //Book book = (Book)it.next();  
  205.         out.print("<tr>");  
  206.         out.print("<td>" + rs.getInt("bid") + "</td>");  
  207.         out.print("<td>" + rs.getString("bName") + "</td>");  
  208.         out.print("<td>" + rs.getInt("bCategory") + "</td>");  
  209.         out.print("<td>" + rs.getString("bDescriptioin") + "</td>");  
  210.         out.print("<td>" + rs.getTimestamp("bAddTime") + "</td>");  
  211.         out.print("<td>" + rs.getString("bMark") + "</td>");  
  212.         out.print("</tr>");  
  213. }  
  214. out.print("<table>");  
  215. rs = null;    
  216. cs = null;  
  217. conn = null;  
  218. %>  
  219. <hr size="1" color="#999999">  
  220. <%   
  221. hs =HibernateSessionFactory.getSession();     
  222. Connection conn2 = hs.connection();     
  223. ResultSet rs2 =null;    
  224. CallableStatement cs2 = conn2.prepareCall("{call getBookByCategoryName(?,?)}");    
  225. cs2.setInt(1,1); //CallableStatement的参数设置下标从1 开始  
  226. cs2.setString(2,"java");  
  227. rs2 = cs2.executeQuery();    
  228. out.print("<br>调用有参数的存储过程:");  
  229. out.print("<table>");  
  230. out.print("<tr bgColor=\"#cdcdcd\">");  
  231. out.print("<td>ID</td>");  
  232. out.print("<td>BookName</td>");  
  233. out.print("<td>categoryID</td>");  
  234. out.print("<td>Description</td>");  
  235. out.print("<td>addTime</td>");  
  236. out.print("<td>mark</td>");  
  237. out.print("</tr>");  
  238. while(rs2.next()){  
  239.         out.print("<tr>");  
  240.         out.print("<td>" + rs2.getInt("bid") + "</td>");  
  241.         out.print("<td>" + rs2.getString("bName") + "</td>");  
  242.         out.print("<td>" + rs2.getInt("bCategory") + "</td>");  
  243.         out.print("<td>" + rs2.getString("bDescriptioin") + "</td>");  
  244.         out.print("<td>" + rs2.getTimestamp("bAddTime") + "</td>");  
  245.         out.print("<td>" + rs2.getString("bMark") + "</td>");  
  246.         out.print("</tr>");  
  247. }  
  248. out.print("<table>");  
  249. rs2=null;    
  250. cs2 = null;  
  251. conn2 = null;  
  252. %>  
  253. <hr size="2" color="blue">  
  254. <p><b>四,通过createSQLQuery方式调用SQL语句/存储过程返回单个或部分字段</b></p>  
  255. <%  
  256. out.print("<br>[无参情况, 求总共有多少本书]: ");  
  257. String totalNum = hs.createSQLQuery("select count(bid) as totalNum from Books").addScalar("totalNum",Hibernate.INTEGER).list().get(0).toString();  
  258. out.print("<br>totalNum = " + totalNum );  
  259. %>  
  260. <hr size="1" color="#999999">  
  261. <%   
  262. out.print("<br>[有参情况, 通过ID找书名]: ");   
  263. SQLQuery query5 = hs.createSQLQuery("select bName as bookName,bAddTime as bookAddTime from Books where bid = ?");  
  264. query5.setInteger(0,1);  
  265. query5.addScalar("bookName",Hibernate.STRING);  
  266. query5.addScalar("bookAddTime",Hibernate.TIMESTAMP);  
  267. String bookName = ((Object[])query5.list().get(0))[0].toString();  
  268. String bookAddTime = ((Object[])query5.list().get(0))[1].toString();  
  269. out.print("<br>条件bid = 1, 查找结果: bookName = " + bookName + " , bookAddTime = " + bookAddTime );  
  270. //上面这里仅取List中的第一个,list中每个元素相当于一条记录,记录中的字段数量跟SQL语句中的字段数量一样;如果取全部,则循环取出来,  
  271. List list5 = query5.list();  
  272. for(int i=0; i<list5.size(); i++){  
  273.     Object[] obj = (Object[])query5.list().get(i); //取出list中第i个元素(即记录),记录中字段数量跟SQL语句中的数量一样    
  274.     out.print("<br>条件bid = 1, 查找结果: bookName = " + obj[0].toString());  
  275.     out.print(" , bookAddTime = " + obj[1].toString());  
  276. }  
  277. %>  
  278.   
  279. <hr size="2" color="blue">  
  280. <p><b>五,通过createQuery方式调用hibernate中映射的XML文件中的HQL语句返回单个或部分或全部字段</b></p>  
  281. <%   
  282.   
  283. %>  
  284. <br>  
  285. <br>  
  286. <br>  
  287. <br>  
  288. <hr size="2" color="blue">  
  289. <p><b>六,通过createSQLQuery方式调用hibernate中映射的XML文件中的SQL语句返回单个或部分或全部字段</b></p>  
  290. <%   
  291.   
  292. %>  
  293. <br>  
  294. <br>参考 http://www.iteye.com/topic/176032  
  295. </body>  
  296. </html>  


涉及函数:

  1. public class Funs {  
  2.     public static String str2UTF8(String refString){  
  3.         //return String width UTF-8 encode  
  4.         if(null == refString || refString.trim().isEmpty()){  
  5.             return "";  
  6.         }  
  7.         String tempString = "";  
  8.         try {  
  9.             tempString = new String(refString.getBytes("ISO-8859-1"),"UTF-8");    
  10.         } catch (Exception e) {  
  11.             tempString = "";  
  12.         }  
  13.         return tempString;  
  14.      }  
  15. }  

引自:http://blog.csdn.net/shenzhennba/article/details/12197539


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值