hql调用mysql存储过程_hibernate调用mysql存储过程
在mysql中創(chuàng)建兩個存儲過程,如下:
1、根據(jù)id查找某條數(shù)據(jù):
1?CREATE?PROCEDURE?`findEmpById`(IN?id?INTEGER(11))2?begin3??????select?*?from?emp?where?empId=id;4?end;
2、根據(jù)id查找某個字段,并返回
1?CREATE?PROCEDURE?`getNameById`(in?id?integer(11),out?eName?varchar(50))2?begin3??????select?empName?into?eName?from?emp?where?empId=id;4?end;
在存儲過程的參數(shù)列表里面,in修飾的參數(shù)代表輸入?yún)?shù),out修飾的代表輸出參數(shù)。
使用hibernate調(diào)用上面兩個存儲過程:
(1)調(diào)用第一個存儲過程
1?package?com.test;?2??3?import?java.sql.CallableStatement;?4?import?java.sql.Connection;?5?import?java.sql.ResultSet;?6?import?java.sql.SQLException;?7??8?import?org.hibernate.Session;?9?import?org.hibernate.SessionFactory;10?import?org.hibernate.cfg.Configuration;11?12?13?public?class?調(diào)用存儲過程?{14?15?????/**16??????*?@param?args17??????*?@throws?SQLException
18??????*/19?????public?static?void?main(String[]?args)?throws?SQLException?{20?????????Configuration?cfg?=?new?Configuration().configure();21?????????SessionFactory?factory?=?cfg.buildSessionFactory();22?????????Session?session?=?factory.openSession();23?????????Connection?con?=?session.connection();24?????????String?sql?=?"{call?findEmpById(?)}";25?????????CallableStatement?cs?=?con.prepareCall(sql);26?????????cs.setObject(1,?2);27?????????ResultSet?rs?=?cs.executeQuery();28?????????while(rs.next()){29?????????????int?id?=?rs.getInt("empId");30?????????????String?name?=?rs.getString("empName");31?????????????System.out.println(id+"\t"+name);32?????????}33?????}34?35?}
調(diào)用存儲過程的sql語句為:call 存儲過程名(參數(shù)...),不過在java中調(diào)用存儲過程一般都加{}。調(diào)用存儲過程使用的是CallableStatement。
(2)調(diào)用第二個存儲過程
1?package?com.test;?2??3?import?java.sql.CallableStatement;?4?import?java.sql.Connection;?5?import?java.sql.SQLException;?6??7?import?org.hibernate.Session;?8?import?org.hibernate.SessionFactory;?9?import?org.hibernate.cfg.Configuration;10?11?public?class?調(diào)用存儲過程1?{12?13?????14?????public?static?void?main(String[]?args)?throws?SQLException?{15?????????Configuration?config?=?new?Configuration().configure();16?????????SessionFactory?sessionFactory?=?config.buildSessionFactory();17?????????Session?session?=?sessionFactory.openSession();18?????????Connection?conn?=?session.connection();19?????????String?sql?=?"{call?getNameById(?,?)}";20?????????CallableStatement?cs?=?conn.prepareCall(sql);
21?????????cs.setObject(1,?3);?//設(shè)置輸出參數(shù)22?????????cs.registerOutParameter(2,?java.sql.Types.VARCHAR);?//設(shè)置第二個參數(shù)為輸出參數(shù)23?????????cs.execute();?//調(diào)用存儲過程24?????????String?name?=?cs.getString(2);//獲取輸出參數(shù)25?????????System.out.println(name);26?????}27?28?}
如果有輸出參數(shù),需要特別指出,如上面的代碼22行
總結(jié)
以上是生活随笔為你收集整理的hql调用mysql存储过程_hibernate调用mysql存储过程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5s换屏幕多少钱啊?
- 下一篇: 吼开头的成语有哪些?