您的位置:首页 > 其它

hibernate中调用存储过程

2013-01-25 17:08 274 查看
/**

* hibernate调用函数的例子

* 不用配置*.hbm.xml文件,直接调用

*/

public void queryFunction()

{

try

{

session = sessionFactory.openSession();

SQLQuery query = session.createSQLQuery("{Call f_login(?,?,?)}");

//输入参数

query.setInteger(0, 1);

query.setString(1, "");

query.setString(2, "");

List list =query.list();

}

catch (RuntimeException re)

{

if (null != tran)

{

tran.rollback();

}

throw re;

}

finally

{

session.close();

}

}

/**

* hibernate调用函数的例子

* @throws SQLException

*/

public void queryFunction2() throws SQLException

{

try

{

//第二种方法

session = sessionFactory.openSession();

Connection conn = session.connection();

ResultSet rs =null;

CallableStatement call = conn.prepareCall("{Call f_login(?,?,?)}");

//输入参数

call.setString(0,"abc");

//输出参数

call.registerOutParameter(1, Types.VARCHAR);

call.registerOutParameter(2,Types.VARCHAR);

rs = call.executeQuery();

if(rs.next()){

System.out.println("存储过程得到的第一个返回值是:"+rs.getString(1));

System.out.println("存储过程得到的第二个返回值是:"+rs.getString(2));

}

}

catch (RuntimeException re)

{

if (null != tran)

{

tran.rollback();

}

throw re;

}

finally

{

session.close();

}

}

/**

* hibernate调用函数的例子

* @throws SQLException

*/

public void queryFunction3() throws SQLException

{

try

{

//第三种方法

session = sessionFactory.openSession();

tran = session.beginTransaction();

//调用*.hbm.xml定义的存储过程(也可以调用*.hbm.xml定义的是SQL语句)

Query query=session.getNamedQuery("login_function");

List list = query.list();

tran.commit();

}

catch (RuntimeException re)

{

if (null != tran)

{

tran.rollback();

}

throw re;

}

finally

{

session.close();

}

}

<!--定义一个调用存储过程的命名SQL查询-->

<sql-query name="login_function" callable="true">

<!-- 返回结果 -->

<return alias="users" class="">

<!-- 将查询到的数据列转换成实体的属性 -->

<return-property name="" column=""/>

</return>

{call f_login(?)}

</sql-query>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: