简体   繁体   中英

how to execute the stored procedure in hibernate 3

I am new in hibernate. I am using hibernate 3 in my application using hibernate annotations , I am developing application in struts 1.3.

My question is : I have googled a lot but could not understand how to call a stored procedure in hibernate using annotations , I have a simple scenario : suppose I have 2 fields in my jsp say 1) code 2) name , I have created a stored procedure in database for inserting those records into table. Now my problem is that how to execute it

 List<MyBean> list = sessionFactory.getCurrentSession()
                          .getNamedQuery("mySp")
                        .setParameter("code", code)
                        .setParameter("name", name)

I don't know the exact code how to do this. But I guess something like that actually I come from jdbc background therefore have no idea how to do this and same thing I want when selecting the data from database using stored procedure.

Hibernate provides many simple ways to call a SP like

  1. Native SQL
  2. Named Query in native SQL as Annotation/XML mapping file

Following link shows how each of above can be implemented

http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#sp_query

Sample to run native SQL query using hibernate:

 Session session = getSession();
    SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(id) FROM tableName WHERE external_id = :external_id");
    sqlQuery.setParameter("external_id", idValue);
    int count = ((BigInteger) sqlQuery.uniqueResult()).intValue();
    releaseSession(session);

You can execute your stored procedure using Hibernate's SQLQuery with the same SQL as when you call it against the database. For example, in postgreSQL:

String query = "select schema.procedure_name(:param1)";
SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(query);
sqlquery.setInteger("param1", "this is first parameter");
sqlQuery.list();

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM