Monday, August 22, 2011

Stored Procedure in Hibernate

//Calling Stored procedure from Hibernate

XXXX.hbm.xml
<sql-query name="del_logged_users" callable="true">
        {call del_logged_users()}
</sql-query>

//Java code to call the stored procedure
public void deleteAllUsersDAO() throws Exception {
        String sql = "{call del_logged_users()}";
        Object[] inputParams = {};
        try    {    
            QueryInput queryInput = PersistenceHelper.createQuery("del_logged_users");
            PersistenceHelper.executeNamedQuery(queryInput);
            
            DatabaseUtil dbUtil = new DatabaseUtil();   //See this class below
            dbUtil.setup(getDataSourceName());
            dbUtil.runCall(sql, inputParams);
        } catch (Exception e) {
            StringBuffer message = new StringBuffer("Error while updating data. Original error message: ").
                append(e.getMessage());
            LogHelper.error(CLASS_NAME, METHOD_NAME, message.toString());
        
            throw new InternalException(
                    BusinessServiceMessageConstants.INT_ERRCODE_JDBC_QUERY_ERROR,
                    message.toString(), e);
        }
}

//Supporting class DatabaseUtil.java
private static HashMap datasourceCache = null;

public void setup(String datasource Name) throws NamingException {
        try {
            synchronized (this) {
                if( datasourceCache == null ) {
                    datasourceCache = new HashMap();
                }
                datasource = (DataSource)datasourceCache.get(datasourceName);
                if( datasource == null ){
                    InitialContext context = new InitialContext();
                    datasource = (DataSource)context.lookup(datasourceName);
                    datasourceCache.put(datasourceName, datasource);
                }
            }   // end synchronized block
        }
        catch(NamingException e) {
            e.printStackTrace();
            //Rethrow the exception
            throw e;
        }
}

public void runCall(String sql, Object[] params) throws SQLException, PersistenceException, 
                                                               RequiredParameterException {
    CallableStatement statement = null;
    Connection connection = getConnection();    
    try {
        statement = connection.prepareCall(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++)    {
                Object par = params[i];
                if (par == null)
                    statement.setNull(i + 1, Types.VARCHAR);
                if (par instanceof String)
                    statement.setString(i + 1, (String) par);
                else if (par instanceof Long)
                    statement.setLong(i + 1, ((Long) par).longValue());
                else if (par instanceof Timestamp)
                    statement.setTimestamp(i + 1, (Timestamp) par);
                else if (par instanceof java.util.Date)
                    statement.setDate(i + 1, new java.sql.Date(((java.util.Date) par)
                            .getTime()));
                else if (par instanceof Integer)
                    statement.setInt(i + 1, ((Integer) par).intValue());
                else if (par instanceof java.math.BigDecimal)
                    statement.setLong(i + 1, ((java.math.BigDecimal) par).longValue());
                // st.setBigDecimal(i+1, (java.math.BigDecimal)par);
            }
        }
        statement.execute();
      //connection.commit(); 
    }
    catch (SQLException e) {
        throw e;
    }
    finally {
        try {            
            if ( statement != null ) {
                statement.close();
            }
            if ( connection != null ) {
                connection.close();
            }
        }
        catch (SQLException e) {        
        } 
    }
}

-----------------------------END----------------------------------------

No comments:

Post a Comment