Spring調用Oracle的Function函數

來源:互聯網
上載者:User

最近搜尋了很多網上講Spring 操作Oracle內部對象的例子,基本上是介紹調用預存程序的~直接調用Oracle內建函式Function的文章真的不多~這裡,法老參考了Spring論壇上外國友人的例子,寫一個DEMO供大家參考~

測試Oracle函數:
Here is a basic function that returns sysdate in a REF CURSOR:

FUNCTION MY_DEMO_FNC
    RETURN    MY_REFCURSOR_PKG.RefCursor
AS    
    return_date MY_REFCURSOR_PKG.RefCursor;
BEGIN
    OPEN return_date FOR 'select  sysdate from dual';
    return return_date;
END MY_DEMO_FNC;

測試程式:
Here is the class that accesses it:import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.object.StoredProcedure;

public class RefCursorTestDao 
...{
  public static void main(String[] args) throws Exception 
  ...{
    new RefCursorTestDao().execute();
  }

  public void execute() throws Exception 
  ...{
    DataSource ds = new DriverManagerDataSource(
        "oracle.jdbc.driver.OracleDriver",
        "jdbc:oracle:thin:@localhost:1521:SID1", 
        "user", "password");

    DemoStoredProcedure proc = new DemoStoredProcedure(ds);
    Map params = new HashMap();
    proc.execute(params);
  }

  private class DemoStoredProcedure extends StoredProcedure 
  ...{
    public static final String SQL = "MY_TEST_PKG.MY_DEMO_FNC";

    public DemoStoredProcedure(DataSource ds) 
    ...{
      setDataSource(ds);
      setSql(SQL);
      setFunction(true);
      declareParameter(
         new SqlOutParameter(
             "whatever", OracleTypes.CURSOR,  new DemoRowMapper()));
      compile();
    }
  }

  private class DemoRowMapper implements RowCallbackHandler 
  ...{
    public void processRow(ResultSet rs) throws SQLException 
    ...{
      System.out.println(rs.getTimestamp(1));
    }
  }
  
}

The process is the same for a real procedure with the REF CURSOR as an OUT parameter, but #setFunction should be false instead of true.
參考地址:http://forum.springframework.org/archive/index.php/t-10054.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.