java call procedure using hibernate

use hibernate to call procedures is not complicate.  

import java.sql.CallableStatement;
import java.sql.Types;
import java.util.List;

import org.hibernate.Session;

import com.core.hibernate.dao.HibernateSessionFactory;

public class Procedure {

//procedures with no return.

@SuppressWarnings(“deprecation”)
public boolean call(String proc, List<Object> params) {
try {
CallableStatement state = null;
Session session = HibernateSessionFactory.getSession();
state = session.connection().prepareCall(proc);
int i = 1;
if (params != null) {
for (Object obj : params) {
if (obj != null) {
state.setObject(i, obj);
} else {
state.setNull(i, Types.NULL);
}
i = i + 1;
}
}
// state.registerOutParameter(i, Types.VARCHAR);
state.execute();
session.close();
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}

// procedure with a string response

@SuppressWarnings(“deprecation”)
public String callwithresponse(String proc, List<Object> params) {
String result = “”;
try {
CallableStatement state = null;
state = HibernateSessionFactory.getSession().connection()
.prepareCall(proc);
int i = 1;
if (params != null) {
for (Object obj : params) {
if (obj != null) {
state.setObject(i, obj);
} else {
state.setNull(i, Types.NULL);
}
i = i + 1;
}
}
state.registerOutParameter(i, Types.VARCHAR);
state.executeQuery();
result = state.getString(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
}

This entry was posted in Computer, Database, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s