hibernate里怎么调用存储过程

存储过程
  CREATE PROCEDURE [dbo].[Rtest] 
@bdate datetime,          //参数
@edate datetime,
@district varchar(6) 
as   
begin 
select s.name,count(i.id) as number  from scenic s,info i where s.id=i.entid and i.usertypeid =303 and i.classid=1 
and (i.pdate between @bdate and  @edate) and s.districtid =@district group by s.name 
end
 
hibernate程序

Session session = HibernateSessionFactory.getSession();

 Connection con=session.connection();   //一定要有
 String procedure = "{call Rtest(?,?,?)}"; 
 CallableStatement cstmt = null;
  ResultSet rs = null;
 try {
 
     cstmt = con.prepareCall(procedure);  //调用存储过程

     //hibernate中一般问号都是从0开始的,但是sql里是从1开始的

     cstmt.setString(1,"2007-9-1");
     cstmt.setString(2,"2007-9-17");  //存储过程里的参数是datetime类型,sql可以自动把String类型转换但是必须是数据库中要的格式 2007/9/7,2007-9-1 都可以

     cstmt.setString(3,"230102");
    rs = cstmt.executeQuery();   //执行
     
    while(rs.next()){
        System.out.println(rs.getInt(2));  //读取
    }
 }finally {
     session.close();             //关闭session
 }

你可能感兴趣的:(sql,Hibernate)