Hibernate3调用存储过程用法

直接以一个例子在说明,如DB2中有一个简单存储过程 selectAllUsers

1. CREATE procedure selectAllUsers
2. DYNAMIC RESULT SETS 1
3. BEGIN
4. DECLARE temp_cursor1 CURSOR WITH RETURN TO CLIENT FOR
5. SELECT * FROM test;
6. OPEN temp_cursor1;
7. END ;


映射文件中关于存储过程内容如下

01. < hibernate-mapping package = "com.unmi.vo" >
02. < class name = "Test" table = "TEST" >
03.      ............
04. </ class >
05.
06. < sql-query callable = "true" name = "selectAllUsers" >
07. < return alias = "aa" class = "Test" >
08. < return-property name = "oborqt" column = "OBORQT" />
09. < return-property name = "moorqt" column = "MOORQT" />
10. < return-property name = "roschn" column = "ROSCHN" />
11. < return-property name = "plandate" column = "PLANDATE" />
12. </ return >
13. { ? = call selectAllUsers() }
14. </ sql-query >
15. </ hibernate-mapping >


{?=callselectAllUsers()}也可以写成{callselectAllUsers()},

如果有参数就写成 {?=callselectAllUsers(?,?,?)}

代码中对query设置相应位置上的值就OK,如

query.setInteger(1,100);
query.setString(2,"Unmi");
query.setDate(3,new Date());

Java调用关键代码如下

1. Session session = HibernateUtil.currentSession();
2. Query query = session.getNamedQuery( "selectAllUsers" );
3. List list = query.list();
4. System.out.println(list);


要求你的存储过程必须能返回记录集,否则要出错
如果你的存储过程是完成非查询任务就应该在配置文件用以下三个标签

1. < sql-insert callable = "true" >{call createPerson (?, ?)}</ sql-insert >
2. < sql-delete callable = "true" >{? = call deletePerson (?)}</ sql-delete >
3. < sql-update callable = "true" >{? = call updatePerson (?, ?)}</ sql-update >


有一点不好的地方就是调用存储过程获取记录集时,不能对Query使用
setFirstResult(int)和setMaxResults(int)方法来分页

你可能感兴趣的:(hibernate3)