如何使用Hibernate con Sql Server 2000调用存储过程?

时间:2014-09-12 19:20:52

标签: java sql-server spring hibernate

我在使用hibernate会话调用存储过程时遇到问题:

Code Java:

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
@Override
public List<Map<String, Object>> buscarCierre(String vanio) throws Exception {
    try {
        List<Map<String, Object>> mapa = new ArrayList<>();
        String queryString = "usp_Cierre_Dia_Obtener_CierrePorAnio :anio, :pagActual, :tamanio";
        Query query = super.getSession().createSQLQuery(queryString);
        query.setString("anio", vanio);
        query.setInteger("pagActual", 1);
        query.setInteger("tamanio", 1);
        List<Object[]> result = query.list(); // requires casting for generics
        for(Object[] obj : result) {
            System.out.println("--- "+obj[0]);
            System.out.println("*** "+obj[1]);
        }


        return mapa;
    } catch (Exception e) {

        e.printStackTrace();

        throw new Exception( getGenerarError(Thread.currentThread().getStackTrace()[1].getMethodName(), 
                             Constantes.NIVEL_APP_DAO,
                             this.getClass().getName(),
                             e.getMessage()) );
    } 
}

从SQL Server 2000调用,是:usp_Cierre_Dia_Obtener_CierrePorAnio '2014',1,1

请帮助我,最后还要检查我是否通过List <Object []>

正确获取数据

错误:

Hibernate: usp_Cierre_Dia_Obtener_CierrePorAnio ?, ?, ?
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 170, SQLState: 37000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Line 1: Incorrect syntax near 'usp_Cierre_Dia_Obtener_CierrePorAnio'.
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)

2 个答案:

答案 0 :(得分:1)

您使用的查询字符串不正确,因此Hibernate生成了无效命令,如:Hibernate: usp_Cierre_Dia_Obtener_CierrePorAnio ?, ?, ?

请参阅Hibernate document以了解如何使用hibernate调用存储过程

此外,SO中还有其他示例显示了我们如何在Hibernate中调用存储过程,例如:

Can I call a stored procedure with hibernate criteria?

How can we call a stored procedure with Hibernate and JPA?

答案 1 :(得分:1)

您可以将存储过程映射到bean,也不要忘记字符串参数的引号:

Query query = session.createSQLQuery("EXEC usp_Cierre_Dia_Obtener_CierrePorAnio :anio, :pagActual, :tamanio").addEntity(<MappedClass>.class);
query.setString("anio", "vanio");
query.setInteger("pagActual", 1);
query.setInteger("tamanio", 1);
List<MappedClass> list = query.list();