简体   繁体   English

无法从休眠中调用存储过程

[英]Unable to call Stored procedure from hibernate

Please try to answer the problem in the below code for calling a stored procedure in ORACLE from hibernate . 请尝试在下面的代码中回答问题,以便从hibernate调用ORACLE中的存储过程。 i am using a named query in hbm file to be called from the testclient.java . 我正在hbm文件中使用一个命名查询,可以从testclient.java进行调用。

Hibernate3.2.1 core file is being used. 正在使用Hibernate3.2.1核心文件。 My stored procedure: 我的存储过程:

create or replace  procedure get_empdetails2(mycursor out sys_refcursor, cond in varchar2)

as 
begin
open mycursor for

select eb.first_name,eb.last_name from employee3 eb where eb.email like cond  ;

end;

Employee.java: Employee.java:

public class Employee{

public Employee()
{
}
    private int eid;
    private String fname,lname,email;
    public int getEid() {
        return eid;
    }
    public void setEid(int eid) {
        this.eid = eid;
    }
    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return lname;
    }
    public void setLname(String lname) {
        this.lname = lname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

table employee3: 表employee3:

Column Name Data Type      Nullable   Default   Primary Key
EID         NUMBER          Yes            -     -
FIRST_NAME  VARCHAR2(20)    Yes            -     -
LAST_NAME   VARCHAR2(20)    Yes            -     -
EMAIL       VARCHAR2(20)    Yes            -     -

hibernate.cfg: hibernate.cfg:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name='connection.url'>jdbc:oracle:thin:@localhost:1521/xe</property>
        <property name='connection.username'>system</property>
        <property name='connection.password'>oracle123</property>
        <property name='connection.driver_class'>oracle.jdbc.driver.OracleDriver</property>
        <property name="show_sql">true</property>
    <mapping resource="employee3.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

Testclient.java Testclient.java

import java.util.*; 
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.Criteria;
public class TestClient
{
   private static SessionFactory factory; 
   public static void main(String[] args)
 {

          System.out.println("--------------done-----------");
            Configuration cfg= new Configuration();
            System.out.println("--------------got cfg object-----------");
            cfg = cfg.configure("hibernate.cfg.xml");
            System.out.println("--------------hbm loaded into cfg-----------");
            SessionFactory sf= cfg.buildSessionFactory();

            System.out.println("--------------done-----------");


System.out.println("--------------getting session-----------");
Session ses =sf.openSession();

Transaction tx = ses.beginTransaction();
System.out.println("--------------got tx object-----------");
Employee eb =null;

SQLQuery q1=(SQLQuery)ses.getNamedQuery("test1");

//q1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);


System.out.println("--------------q1 processing-----------");
//q1.setInteger(0,0);
q1.setString(0,"v%");

//q1.setParameter(0, "%a%");
System.out.println("--------------q1 processing-----------");
List res=q1.list();
System.out.println(res);

tx.commit();
ses.close();

System.out.println("--------------closing connection-----------");
sf.close();
System.out.println("--------------connection closed-----------");



}}

employee3.hbm: employee3.hbm:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 


          <hibernate-mapping>
          <class name="Employee" table="employee3">
            <id name="eid" column="eid"/>
      <property name="fname" column="first_name"/>
      <property name="lname" column="last_name"/>
      <property name="email" column="email"/>
   </class>


 <sql-query name="test1" callable="true">
 <return  alias ="test1" class ="Employee">
    <return-property name="fname" column="FIRST_NAME"/>
    <return-property name="lname" column="LAST_NAME"/>
</return> 

  {call get_empdetails2(?,?)}

</sql-query>

</hibernate-mapping>

In the call get_empdetails(?,?) , the first ? 在调用get_empdetails(?,?)中,第一个? is used for output mycursor which as per the hibernate doc must be the first parameter and second ? 用于输出mycursor,根据休眠文档,它必须是第一个参数,第二个是? is the input parameter for the cond variable in procedure. 是过程中cond变量的输入参数。 My output error is : 我的输出错误是:

 Oct 10, 2014 2:38:54 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
 INFO: indexes: [] Oct 10, 2014 2:38:54 PM

  org.hibernate.tool.hbm2ddl.SchemaUpdateexecuteINFO:schema update complete  
   --------------done-----------  
   --------------getting session-----------  
   --------------got tx object----------- 
   --------------q1 processing----------- 
   --------------q1 processing----------- 
   Hibernate: {call get_empdetails2(?,?)}
   Oct 10, 2014 2:38:54 PM org.hibernate.type.NullableType nullSafeGet
   INFO: **could not read column value from result set: eid0_0_; Invalid column name**  
   Oct 10, 2014 2:38:54 PM org.hibernate.util.JDBCExceptionReporter logExceptions  
   WARNING: SQL Error: 17006, SQLState: null  
   Oct 10, 2014 2:38:54 PM org.hibernate.util.JDBCExceptionReporter logExceptions 
   SEVERE: Invalid column name  Exception in thread "main" 

  org.hibernate.exception.GenericJDBCException: could not execute query at
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
  at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
  at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
  at org.hibernate.loader.Loader.doList(Loader.java:2214)
  at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2095)
  at org.hibernate.loader.Loader.list(Loader.java:2090)
  at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
  at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
  at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
  at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:150)
  at TestClient.main(TestClient.java:44)    
  Caused by: java.sql.SQLException: Invalid column name 
  at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)  

As present in the output , i am getting this - could not read column . 如输出中所示,我正在获取此信息-无法读取列。 whats wrong in the configuration? 配置有什么问题?

Thanks 谢谢

Hibernate is trying to map whole table from return result of Stored Procedure. Hibernate尝试根据存储过程的返回结果映射整个表。 You are returning eb.first_name,eb.last_name from Stored Procedure. 您正在从存储过程中返回eb.first_name,eb.last_name

Possible Solution 1: 可能的解决方案1:

Select all field in Stored Procedure SELECT query like select * from employee3 eb where eb.email like cond ; 在存储过程SELECT查询中选择所有字段,例如select * from employee3 eb where eb.email like cond ;

If solution 1 works for you then use it but if you want to return only two fields from stored procedure I'd suggest you second solution. 如果解决方案1适合您,则可以使用它,但是如果您只想从存储过程中返回两个字段,我建议您使用第二种解决方案。 As I don't know how we can execute named query which returns only selected fields. 我不知道如何执行仅返回选定字段的命名查询。

Possible Solution 2: 可能的解决方案2:

Use SQLQuery . 使用SQLQuery I used it with MySQL You can try for Oracle . 我将它与MySQL一起使用。可以尝试使用Oracle Hope it will work. 希望它能工作。

Query callStoredProcedure_MYSQL = session.createSQLQuery("CALL SP_MYSQL_HIBERNATE (:param1, :param2, :param3)");
callStoredProcedure_MYSQL.setInteger("param1", 10);
callStoredProcedure_MYSQL.setInteger("param2", 10);
callStoredProcedure_MYSQL.setString("param3", "test");*/

/* callStoredProcedure_MYSQL.list() will execute stored procedure and return the value */
List customResult = callStoredProcedure_MYSQL.list();
if (customResult != null && !customResult.isEmpty()) {
 Object[] obj = customResult.get(0);
 System.out.println(obj[0]);
 System.out.println(obj[1]);            
}

我们有相同的错误,但我可以通过在存储过程所在的位置添加数据库名称来解决:

Query query = session.createSQLQuery("CALL db_Name.storeprocedureName(:parameter)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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