NOT Using Named Parameters in a Native Query

Hi!
like it is written in the Toplink JPA Extensions reference Toplink supports using named parameters in native queries.
See example from http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-extensions.html:
Example 1-11 Specifying a Named Parameter With #
Query queryEmployees = entityManager.createNativeQuery(
"SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = #firstname"
queryEmployeeByFirstName.setParameter("firstName", "Joan");
Collection employees = queryEmployees.getResultList();
But I want to use "#" in the SQL statement so I want to disable this parameter binding somehow and let the query just execute the SELECT statement I deliver.
I have tried to add the property
<property name="toplink.jdbc.bind-parameters" value="false"/>
into the persistence.xml and I have also tried to add the query hint
query.setHint(TopLinkQueryHints.BIND_PARAMETERS, HintValues.FALSE);
but none of them prevents the # to be uses as a paramter. this causes the exception:
Exception [TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryException
Exception Description: Query argument ######' not found in list of parameters provided during query execution.
Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
The SQL Statement is
SELECT * FROM TABLE (
CAST ( RCGC.PHA_P_COMPASMDM.LookupSimilarMats
( 'COC003','10021500150000000997','30','30','040','standard','','001001','001001','123456','##########','X','X','X','X','U' )
AS RCGC.PHA_COMPAS_SIMILAR_MATS ) )
I am using the latest Toplink essentials build together with an Oracle 9.2i DB in a Java SE web application.
Can anyone give me a little hint what to do?
Thanks and best regards,
Alex

I hope this is what you need:
[TopLink Fine]: 2007.01.19 02:56:48.278--ServerSession(17712783)--Connection(723185)--Thread(Thread[http-8080-Processor2
3,5,main])--SELECT APPL_CGP_MATLOC, CHANGE_REQ_MATLOC, CD_PHA_MAT_LOC, LCOMP, LOC_MAT_NAME, APPL_GDM_MATLOC, LOC_MAT_NAM
E_SHORT, APPL_PDW_MATLOC, PHA_MAT_LOC_LCOMMENT, APPL_TP_MATLOC, DIVISION, APPL_WRS_MATLOC, ARTICLE_ID_MDA, LU_PHA_MAT_LO
C, LOC_MAT_NAME_OLD, LDT_PHA_MAT_LOC, PHA_MAT_LOC_STATUS, CU_PHA_MAT_LOC, MAT_LOC_ID, RCOMP, MAT_ID FROM RCGC.PHA_V_COMP
AS_MAT_MATLOC WHERE ((MAT_LOC_ID = '123456') AND (RCOMP = '001001'))
[TopLink Fine]: 2007.01.19 02:56:48.398--ServerSession(17712783)--Connection(32404901)--Thread(Thread[http-8080-Processo
r23,5,main])--SELECT MAT_ID, DESCRIPTION, PHA_MATERIAL_LCOMMENT, PACKSIZE, LU_PHA_MATERIAL, PACKSIZE_UNIT, LDT_PHA_MATER
IAL, CONTAINER_NAME, CU_PHA_MATERIAL, PURPOSE, CD_PHA_MATERIAL, CONTENT, CONTAINER_ID, AI_FACTOR, PHA_MATERIAL_STATUS, C
MG_SPEC_APP, PROD_LEVEL, PACKAGE_SIZE, PRODUCT_ID FROM RCGC.PHA_V_COMPAS_MATERIAL WHERE (MAT_ID = '10021500150000000997'
[TopLink Fine]: 2007.01.19 02:56:48.468--ServerSession(17712783)--Connection(723185)--Thread(Thread[http-8080-Processor2
3,5,main])--SELECT PRODUCT_ID, PROD_GRP_ID, APPL_FORM_NAME, PRODUCT_NAME, GALENIC_FORM_NAME, APPL_FORM_ID, PHA_PRODUCT_S
TATUS, PHA_PRODUCT_LCOMMENT, GALENIC_FORM_ID, LU_PHA_PRODUCT, INN, LDT_PHA_PRODUCT FROM RCGC.PHA_V_COMPAS_PRODUCT WHERE
(PRODUCT_ID = 'COC003')
[TopLink Fine]: 2007.01.19 02:56:48.568--ServerSession(17712783)--Connection(32404901)--Thread(Thread[http-8080-Processo
r23,5,main])--SELECT APPL_CGP_MATLOC, CHANGE_REQ_MATLOC, CD_PHA_MAT_LOC, LCOMP, LOC_MAT_NAME, APPL_GDM_MATLOC, LOC_MAT_N
AME_SHORT, APPL_PDW_MATLOC, PHA_MAT_LOC_LCOMMENT, APPL_TP_MATLOC, DIVISION, APPL_WRS_MATLOC, ARTICLE_ID_MDA, LU_PHA_MAT_
LOC, LOC_MAT_NAME_OLD, LDT_PHA_MAT_LOC, PHA_MAT_LOC_STATUS, CU_PHA_MAT_LOC, MAT_LOC_ID, RCOMP, MAT_ID FROM RCGC.PHA_V_CO
MPAS_MAT_MATLOC WHERE (MAT_ID = '10021500150000000997')
[TopLink Warning]: 2007.01.19 02:56:48.638--UnitOfWork(4469532)--Thread(Thread[http-8080-Processor23,5,main])--Exception
[TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryException
Exception Description: Query argument ######' not found in list of parameters provided during query execution.
Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
Local Exception Stack:
Exception [TOPLINK-6132] (Oracle TopLink Essentials - 9.1 (Build b22)): oracle.toplink.essentials.exceptions.QueryExcept
ion
Exception Description: Query argument ######' not found in list of parameters provided during query execution.
Query: ReadAllQuery(de.merck.compas.material.SimilarLocalMaterialListItemBV)
at oracle.toplink.essentials.exceptions.QueryException.namedArgumentNotFoundInQueryParameters(QueryException.jav
a:206)
at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.getValueForInParameter(DatasourceCall.java:6
86)
at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.getValueForInOutParameter(DatasourceCall.jav
a:704)
at oracle.toplink.essentials.internal.databaseaccess.DatasourceCall.translateQueryString(DatasourceCall.java:630
at oracle.toplink.essentials.internal.databaseaccess.DatabaseCall.translate(DatabaseCall.java:850)
at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQuer
yMechanism.java:212)
at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQuer
yMechanism.java:199)
at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCa
llQueryMechanism.java:270)
at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQu
eryMechanism.java:600)
at oracle.toplink.essentials.queryframework.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:302)
at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:
709)
at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:609)
at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:677)
at oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:7
31)
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2218)
at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:937)
at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:909)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:346)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getResultList(EJBQueryImpl.java:447)
at de.merck.compas.material.SimilarLocalMaterialListItemBC.selectList(SimilarLocalMaterialListItemBC.java:40)
at de.merck.compas.material.SimilarLocalMaterialListItemBC.selectSimilar(SimilarLocalMaterialListItemBC.java:53)
at de.merck.compas.material.MaterialMaintainFS.init(MaterialMaintainFS.java:158)
at de.merck.compas.material.MaterialListSV.startMaterialMaintain(MaterialListSV.java:186)
at de.merck.compas.material.MaterialListSV.processPage(MaterialListSV.java:97)
at de.merck.jsfw.servletFramework.AbstractServlet.processPage(AbstractServlet.java:141)
at de.merck.jsfw.servletFramework.ControllerServlet.processLastPage(ControllerServlet.java:240)
at de.merck.jsfw.servletFramework.ControllerServlet.processRequest(ControllerServlet.java:206)
at de.merck.jsfw.servletFramework.ControllerServlet.doGet(ControllerServlet.java:181)
at de.merck.jsfw.servletFramework.ControllerServlet.doPost(ControllerServlet.java:191)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at de.merck.comp.ntml.NTLMFilter.negotiate(NTLMFilter.java:384)
at de.merck.comp.ntml.NTLMFilter.doFilter(NTLMFilter.java:165)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:432)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java
:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
The Toplink manifest file with version number:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 1.5.0_09-b03 (Sun Microsystems Inc.)
Specification-Title: Java Persistence API
Specification-Vendor: Sun Microsystems, Inc., Oracle Corp.
Specification-Version: 1.0
Implementation-Title: TopLink Essentials
Implementation-Vendor: Sun Microsystems, Inc., Oracle Corp.
Implementation-Version: 9.1 build: b22
Thanks again for your help!

Similar Messages

  • JavaDB or Toplink not recognizing named parameters?

    Creating a query within a session bean but the named parameter is causing an exception. Using Derby with Toplink in the Sun App Server 9.0_01. Any ideas what the problem or solution is?
        public String getNumberOfInvoices(String supplierAccount) {
            String suppAcc = "";
            Query qry = em.createNativeQuery(
                    "select count(d) from App.Documents as d " +
                    "where d.PERSONALACCOUNT = :suppAcc;");
            qry.setParameter("suppAcc", supplierAccount);
            Long count = (Long) qry.getSingleResult();
            return Long.toString(count);
    [#|2007-09-22T23:41:09.271+0100|WARNING|sun-appserver-pe9.0|oracle.toplink.essentials.file:/C:/Sun/SDK/domains/domain1/applications/j2ee-apps/Accounting/Accounting-ejb_jar/-Accounting-ejbPU|_ThreadID=16;_ThreadName=httpWorkerThread-8080-1;_RequestID=4ffb3c50-34f3-42cf-a00b-26e93a0f8ed6;|
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: org.apache.derby.client.am.SqlException: Syntax error: Encountered ":" at line 1, column 67.Error Code: -1
    Call:select count(d) from App.Documents as d where d.PERSONALACCOUNT = :suppAcc;
    Query:DataReadQuery()
         at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:303)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:551)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:437)
         at oracle.toplink.essentials.threetier.ServerSession.executeCall(ServerSession.java:465)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:213)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:199)

    This seems to have resolved the problem to a degree. I am not sure why
    numeric parameters are accepted but named one are not. I don't know. I can do named parameters with Hibernate. I don't know TopLink.
    You understand that "named query" is different from "query with named parameters", right? You seem to want the latter, not the former. Maybe you're reading the wrong docs.
    I have also
    changed from count(d) to count(*). Is this because I am using EJB Query
    Language but createNativeQuery is plain JDBC?
    If you're counting all the rows in a table, it would be count(*). If you want to only count certain rows, it'd be a GROUP BY and HAVING.
    Any way the error is now saying:-
    Caused by: java.lang.ClassCastException: java.util.Vector cannot be cast
    to java.lang.Long
    This is pretty clear. You're assuming that the method returns a Long and it's telling you that it returns a Vector. It should only have size 1, and you should get the zeroth index value out of it.
    %

  • Using named parameters with an sql UPDATE statement

    I am trying to write a simple? application on my Windows 7 PC using HTML, Javascript and Sqlite.  I have created a database with a 3 row table and pre-populated it with data.  I have written an HTML data entry form for modifying the data and am able to open the database and populate the form.  I am having trouble with my UPDATE function.  The current version of the function will saves the entry in the last row of the HTML table into the first two rows of the Sqlite data table -- but I'm so worn out on this that I can't tell if it is accidental or the clue I need to fix it.
    This is the full contents of the function . . .
         updateData = new air.SQLStatement();
         updateData.sqlConnection = conn;
         updateData.text = "UPDATE tablename SET Gsts = "Gsts, Gwid = :Gwid, GTitle = :GTitle WHERE GId = ":GId;
              var x = document.getElementsById("formname");
              for (var i = 1, row, row = x.rows[i]; i++) {
                   updateData.parameters[":GId"] = 1;
                   for (var j = 0, col; col=row.cells[j]; j++) {
                        switch(j) {
                             case 0: updateData.parameters[":GTitle"] = col.firstChild.value; break;
                             case 1: updateData.parameters[":Gsts"] = col.firstChild.value; break;
                             case 2: updateData.parameters[":Gwid"] = col.firstChild.value; break;
    Note: When I inspect the contents of the col.firstChild.value cases, they show the proper data as entered in the form -- it just isn't being updated into the proper rows of the Sqlite table.
    Am I using the named parameters correctly? I couldn't find much information on the proper use of parameters in an UPDATE statement.

    Thank you for the notes.  Yes, the misplaced quotes were typos.  I'm handtyping a truncated version of the function so I don't put too much info in the post. And yes, i = 1 'cuz the first rows of the table are titles.  So the current frustration is that I seem to be assigning all the right data to the right parameters but nothing is saving to the database.
    I declare updateData as a variable at the top of the script file
    Then I start a function for updating the data which establishes the sql connection as shown above.
    The correctly typed.text statement is:
            updateData.text = "UPDATE tablename SET Gsts=:Gsts, Gwid=:Gwid, GTitle=:GTitle WHERE GId=:GId";
    (The data I'm saving is entered in text boxes inside table cells.) And the current version of the loop is:
            myTable = document.getElementById("GaugeSts");
            myRows= myTable.rows;
              for(i=1, i<myRows.length, i++) {
                   updateData.parameters[":GId"]=i;
                   for(j=0; j<myRows(i).cells.length, j++) {
                        switch(y) {
                             case 0: updateData.parameters[":GTitle"]=myrows[i].cells[y].firstChild.value; break;
                             case 1: updateData.parameters[":Gsts"]=myrows[i].cells[y].firstChild.value; break;
                             case 2: updateData.parameters[":Gwid"]=myrows[i].cells[y].firstChild.value; break;
                             updateData.execute;
    The whole thing runs without error and when I include the statements to check what's in myrows[i].cells[y].firstChild.value, I'm seeing that the correct data is being picked up for assignment to the parameters and the update. I haven't been able to double check that the contents of the parameters are actually taking the data 'cuz I don't know how to extract the data from the parameters. ( The only reference  I've found so far has said that it is not possible. I'm still researching that one.) I've also tried moving the position of the updateData execution statement to several different locations in the loop andstill nothing updates. 
    I am using a combination of air.Introspector.Console.log to check the results of code and I'm using Firefox's SQlite manager to handle the database.  The database is currently sitting on the Desktop to facilitate testing and I have successfully updated/changed data in this table through the SQLite Manager so I don't think I'm having permission errors and, see below, I have another function successfully saving data to another table.
    I currently have another function that uses ? for the parametersin the .text of a INSERT/REPLACE statement and that one works fine.  But, only one line of data is being saved so there is no loop involved.  I tried changing the UPDATE statement in this function to the INSERT/REPLACE just to make something save back to the database but I can't make that one work either.I've a (And, I've tried so many things now, I don't even remember what actually saved something --albeit incorrectly --to the database in one of my previous iterations with the for loops.)
    I'm currently poring through Sqlite and Javascript tomes to see if I can find what's missing but if anything else jumps out at you with the corrected code, I'd appreciate some ideas.
    Jeane

  • Not using Index when SDO_RELATE in Spatial Query is used in LEFT OUTER JOIN

    I want to know for every City (Point geometry) in which Municipality (Polygon geometry) it is.
    Some cities will not be covered by any municipality (as there is no data for it), so its municipality name should be blank in the result
    We have 4942 cities (point geometries)
    and 500 municipalities (polygon geometry)
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1
    LEFT OUTER JOIN MUNICIPALITY T2 ON SDO_RELATE(T1.GEOM, T2.GEOM, 'MASK=ANYINTERACT') = 'TRUE'The explain plan for this query is:
    SELECT STATEMENT
      FILTER
        Filter Predicates
          MDSYS.SDO_RTREE_RELATE(T1.GEOM, T2.GEOM, 'mask=ANYINTERACT querytype=window ') = 'TRUE'
        MERGE JOIN
          TABLE ACCESS              CITY               FULL                            11
          BUFFER                                       SORT                        100605
              TABLE ACCESS          MUNICIPALITY       FULL                            20So the cost is in the BUFFER (whatever that is), it takes +2000 seconds to run this, it is not using the spatial index.
    And we are not getting all rows, but only the ones interacting with a municipality, e.g. 2436 rows.
    But I want all rows, including the ones not interacting with any Municipality.
    When we want only those cities that actually are in a municipality, I use a different query and it will use the index.
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1, MUNICIPALITY T2
    WHERE SDO_RELATE(T1.GEOM, T2.GEOM, 'MASK=ANYINTERACT') = 'TRUE'I get (only) 2436 rows (as expected) in 5 seconds (it is fast) and the explain plan shows it is using the spatial index.
    But in this case, I am not getting any cities not inside any municipality (of course)
    SELECT STATEMENT
       NESTED LOOPS
          TABLE ACCESS                   MUNICIPALITY       FULL                22
          TABLE ACCESS                   CITY               BY INDEX ROWID      22
             DOMAIN INDEX                CITY_SDX                                0
                Access Predicates
                   MDSYS.SDO_RTREE_RELATE(T1.GEOM, T2.GEOM, 'mask=ANYINTERACT querytype=window ') = 'TRUE'I always thought a LEFT OUTER JOIN would return all rows from the Table, whatever happens in the next,
    but it seems the query has been rewritten so that it is now using a Filter Predicate in the end, which filters those geometries having no interaction.
    As an example I also do thing alphanumerically, I do get 4942 rows, including the ones which have no Municipality name.
    In this case the names must match, so its only for testing if the LEFT OUTER JOIN returns stuff correctly, which it does in this case.
    SELECT T1.NAME as City, T2.NAME as Municipality
    FROM CITY T1
    LEFT OUTER JOIN MUNICIPALITY T2 ON T1.NAME = T2.NAMEIs this an Oracle Spatial bug, e.g. not return 4942 rows, but only 2436 rows on the first query?
    Note all tests performed on Oracle 11g R2 (11.2.0.1.0)

    Patrick,
    Even so, your geoms in the relate were the wrong way around.
    Also, I don't recall you saying (or showing) that you wanted the municipality geometry returned. Still,
    no matter, easy to do.
    Here are some additional suggestions. I don't have your data so I have had to use some of my own.
    set serveroutput on timing on autotrace on
    SELECT T1.SPECIES as City,
           (SELECT T2.ADMIN_NAME FROM AUSTRALIAN_STATES T2 WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE') as Municipality,
           (SELECT T2.GEOM       FROM AUSTRALIAN_STATES T2 WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE') as geom
      FROM GUTDATA T1;
    762 rows selected
    Elapsed: 00:00:21.656
    Plan hash value: 2160035213
    | Id  | Operation                   | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |                            |   762 | 49530 |     5   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| AUSTRALIAN_STATES          |     1 |   115 |     0   (0)| 00:00:01 |
    |*  2 |   DOMAIN INDEX              | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   3 |  TABLE ACCESS BY INDEX ROWID| AUSTRALIAN_STATES          |     1 |   115 |     0   (0)| 00:00:01 |
    |*  4 |   DOMAIN INDEX              | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   5 |  TABLE ACCESS FULL          | GUTDATA                    |   762 | 49530 |     5   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       4 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
               24576  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksThe above can look messy as you add more (SELECT ...) attributes, but is is fast (though can't use in Materialized Views).
    /* The set of all cities not in municipalities */
    SELECT T1.SPECIES                 as City,
           cast(null as varchar2(42)) as municipality,
           cast(null as sdo_geometry) as geom
      FROM GUTDATA T1
    WHERE NOT EXISTS (SELECT 1
                         FROM AUSTRALIAN_STATES T2
                        WHERE SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    UNION ALL
    /* The set of all cities in municipalities */
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality,
           T2.GEOM       as geom
      FROM GUTDATA T1
           INNER JOIN
           AUSTRALIAN_STATES T2 ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');
    762 rows selected
    Elapsed: 00:00:59.953
    Plan hash value: 2854682795
    | Id  | Operation           | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |                            |    99 | 13450 |    38  (87)| 00:00:01 |
    |   1 |  UNION-ALL          |                            |       |       |            |          |
    |*  2 |   FILTER            |                            |       |       |            |          |
    |   3 |    TABLE ACCESS FULL| GUTDATA                    |   762 | 49530 |     5   (0)| 00:00:01 |
    |*  4 |    DOMAIN INDEX     | AUSTRALIAN_STATES_GEOM_SPX |       |       |     0   (0)| 00:00:01 |
    |   5 |   NESTED LOOPS      |                            |    61 | 10980 |    33   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL| AUSTRALIAN_STATES          |     8 |   920 |     3   (0)| 00:00:01 |
    |*  7 |    TABLE ACCESS FULL| GUTDATA                    |     8 |   520 |     4   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - filter( NOT EXISTS (SELECT 0 FROM "AUSTRALIAN_STATES" "T2" WHERE "MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE'))
       4 - access("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"(:B1,10000,0.5,'UNIT=M'))='TRUE')
       7 - filter("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
              131072  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksMuch slower but Materialized View friendly.
    This one is a bit more "natural" but still slower than the first.
    set serveroutput on timing on autotrace on
    /* The set of all cities in municipalities */
    WITH municipal_cities As (
      SELECT T1.ID         as City,
             T2.ADMIN_NAME as Municipality,
             T2.GEOM       as geom
        FROM GUTDATA T1
             INNER JOIN
             AUSTRALIAN_STATES T2 ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    SELECT T1.ID           as City,
           T2.Municipality as Municipality,
           T2.GEOM         as geom
      FROM GUTDATA          T1
           LEFT OUTER JOIN
           municipal_cities T2
           ON (T2.CITY = T1.ID);
    762 rows selected
    Elapsed: 00:00:50.228
    Plan hash value: 745978991
    | Id  | Operation             | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |                   |   762 | 44196 |    36   (3)| 00:00:01 |
    |*  1 |  HASH JOIN RIGHT OUTER|                   |   762 | 44196 |    36   (3)| 00:00:01 |
    |   2 |   VIEW                |                   |    61 |  3294 |    33   (0)| 00:00:01 |
    |   3 |    NESTED LOOPS       |                   |    61 | 10980 |    33   (0)| 00:00:01 |
    |   4 |     TABLE ACCESS FULL | AUSTRALIAN_STATES |     8 |   920 |     3   (0)| 00:00:01 |
    |*  5 |     TABLE ACCESS FULL | GUTDATA           |     8 |   520 |     4   (0)| 00:00:01 |
    |   6 |   INDEX FAST FULL SCAN| GUTDATA_ID_PK     |   762 |  3048 |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("T2"."CITY"(+)="T1"."ID")
       5 - filter("MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
               49152  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksFinally, the Pièce de résistance: trick the LEFT OUTER JOIN operator...
    set serveroutput on timing on autotrace on
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality,
           T2.GEOM       as geom
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (t2.admin_name = to_char(t1.ID) OR
               SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');
    762 rows selected
    Elapsed: 00:00:50.273
    Plan hash value: 158854308
    | Id  | Operation           | Name              | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |                   |   762 | 92964 |  2294   (1)| 00:00:28 |
    |   1 |  NESTED LOOPS OUTER |                   |   762 | 92964 |  2294   (1)| 00:00:28 |
    |   2 |   TABLE ACCESS FULL | GUTDATA           |   762 | 49530 |     5   (0)| 00:00:01 |
    |   3 |   VIEW              |                   |     1 |    57 |     3   (0)| 00:00:01 |
    |*  4 |    TABLE ACCESS FULL| AUSTRALIAN_STATES |     1 |   115 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - filter("T2"."ADMIN_NAME"=TO_CHAR("T1"."ID") OR
                  "MDSYS"."SDO_ANYINTERACT"("T2"."GEOM","SDO_GEOM"."SDO_BUFFER"("T1"."GEOM",10000,0.5,'UNIT=M'))='TRUE')
       Statistics
                   7  user calls
                   0  physical read total bytes
                   0  physical write total bytes
                   0  spare statistic 3
                   0  commit cleanout failures: cannot pin
                   0  TBS Extension: bytes extended
                   0  total number of times SMON posted
                   0  SMON posted for undo segment recovery
                   0  SMON posted for dropping temp segment
                   0  segment prealloc tasksTry these combinations to see what works for you.
    Interestingly, for me, the following returns absolutely nothing.
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE')
    MINUS
    SELECT T1.SPECIES    as City,
           T2.ADMIN_NAME as Municipality
      FROM GUTDATA           T1
           LEFT OUTER JOIN
           AUSTRALIAN_STATES T2
           ON (t2.admin_name =  to_char(t1.ID) OR
               SDO_ANYINTERACT(T2.GEOM, SDO_GEOM.SDO_BUFFER(T1.GEOM,10000,0.5,'UNIT=M')) = 'TRUE');(I leave it to you to see if you can see why as the LEFT OUTER JOIN seems to be working correctly for me but I am not going to dedicate time to detailed checking of results.)
    Note all tests performed on Oracle 11g R2 (11.2.0.1.0)
    If you get the answer you want: mark the post as answered to assign points.
    regards
    Simon

  • CallableStatement using named parameters: is that possible?

    Hi,
    Can I use named parameter in a statement to be executed with CallableStatement, in stead of using :1, :2, etc ?
    thanks
    Ronny

    Your question is a little ambiguous. However, I will try to answer it.
    You need to use a program to send the email for you. On Solaris by default this is sendmail. However, it can be used in a number of modes.
    1. It can be run as a daemon, listening on port 25 for new messages to be delivered to it.
    This is enabled by default but is not necessary for sending email. If you wish to switch sendmail off as a service in Solaris10 then you should type 'svcadm disable svc:/network/smtp:sendmail'. If you wish to switch it off on earlier Solaris releases you will need to move/erase the startup script in either /etc/rc2.d or /etc/rc3.d.
    2. It can be run in 'immediate mode' to send mail immediately.
    This allows you to send a mail directly to someone. On a normally configured sendmail instance it will try to deliver the mail immediately - if the server at the other end is unavailable, the mail will be queued locally to be potentially delivered at a later date.
    3. It can run in delivery only mode to attempt to send queued mail
    Queued mail will not automatically get processed. Sendmail needs to run at a later date to attempt to deliver any queued mail. This can either be done via cron using 'sendmail -q' or sendmail can be left running the whole time and told to rerun the queue in given periods ie 'sendmail -q15m'
    There are alternatives to sendmail for delivering mail - postfix, exim, qmail are just three examples. I would advise against trying to deliver mail without using a specific mail agent to do it. Whilst the SMTP mail protocol is pretty simple in basic use cases the protocol does get complex. There is no real downside in using an established program.
    HTH.

  • Native TopLink named query with named parameters

    Hello,
    Defining my metadata in native TopLink xml and using the native TopLink's Session interface I can access and successfully execute a named query using positional parameters (parameters passed to match the ?1 ?2 etc). I used for this the Session.executeQuery(String, Class, List) method e.g.
    select p from Person p where p.name = ?1
    Now, how can I get the same Session to execute named queries using named parameters? None of the Session.executeQuery methods seem suitable ... Am I missing anything here? e.g.
    select p from Person p where p.age = :age
    I can't find in Session http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/b13698/oracle/toplink/sessions/Session.html a good match for this use-case. I would expect something like:
    Session.executeQuery(String queryName, Class target, List argNames, List argValues)
    or
    Session.executeQuery(String queryName, Class target, Map argsKeyedByName)
    but can't find any good match, can anyone please enlighten me?
    Thanks in advance,
    Best regards,
    Giovanni

    Hello Chris,
    Many thanks for your response. I am sorry if I did not explain my problem properly.
    Suppose I already defined a named query in the metadata XXXProject.xml using the <opm:querying ... this JPQL named query "customFinder" already exists and would look something like:
    select p from Person p where p.firstname=:firstname and p.lastname=:lastname and p.birthdate=:birthdate
    now say you want to execute this query from the Session:
    Vector args = new Vector();
    // how do you know the order? you shouldn't know the order!
    // you know only the parameter names and that's what I mean
    // about named parameters
    // This args setup is wrong ... I need a way to specify to which
    // parameter name each argument corresponds to. In other words
    // if the named query where criteria order of parameters is modified
    // perhaps because of pruning composite keys etc you won't break the
    // existing code ...
    args.add(new Date());
    args.add("Azua");
    args.add("Giovanni");
    Session session = ...
    session.executeQuery("customFinder", Person.class, args);
    JPA supports both type of queries positional parameters and named parameters. Your explanation above is only for the first, my question refers to the later.
    I have not yet found the api for this ... though I am investigating along the lines of:
    Query query = session.getQuery("customFinder");
    and then try to assign the arguments in the same order that the parameters are defined in query or?
    Thanks in advance,
    Best regards,
    Giovanni
    Edited by: bravegag on 29.05.2009 08:06

  • Parameters in Native Query?

    How can I add parameters to a native query?
    The following approach does not work.
    String query = "select * from a where type=:type";
    Query q = em.createNativeQuery(query, A.class);
    q.setParameter("type", 7);
    q.getResultList();
    I get the following exception:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060908)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':type AND contains(GeomFromText('POLYGON((2.47 51.037,4.66 51.037,4.66 51.86,2.4' at line 1Error Code: 1064
    Call:SELECT count(*) AS num FROM shipaction WHERE actiontype_id=:type AND contains(GeomFromText('POLYGON((2.47 51.037,4.66 51.037,4.66 51.86,2.47 51.86,2.47 51.037))'),current_pos)
    Query:ResultSetMappingQuery()
    at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:303)
    at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:551)
    at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:437)
    at oracle.toplink.essentials.threetier.ServerSession.executeCall(ServerSession.java:465)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:213)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:199)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:270)
    at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeSelect(DatasourceCallQueryMechanism.java:252)
    at oracle.toplink.essentials.queryframework.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:198)
    at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:609)
    at oracle.toplink.essentials.queryframework.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:536)
    at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2218)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:937)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:909)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:346)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:471)
    at com.vesseltracker.session.ShipactionUtilBean.countByPolygonAndActionType(ShipactionUtilBean.java:101)

    Hello,
    I had tried it on OC4J with Oracle:
    If q.setParameter(1, 7) had been written
    I've got:
    06/11/16 13:12:01 java.lang.ArrayIndexOutOfBoundsException: 1 > 0
    06/11/16 13:12:01      at java.util.Vector.insertElementAt(Vector.java:558)
    06/11/16 13:12:01      at java.util.Vector.add(Vector.java:776)
    06/11/16 13:12:01      at oracle.toplink.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:349)
    06/11/16 13:12:01      at oracle.toplink.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:178)
    06/11/16 13:12:01      at com.desyde.tmsissue.model.ejb.session.IssueHoursSessionBean.getIssueHoursById(IssueHoursSessionBean.java:74)
    06/11/16 13:12:01      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    06/11/16 13:12:01      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    06/11/16 13:12:01      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    06/11/16 13:12:01      at java.lang.reflect.Method.invoke(Method.java:585)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.joinpoint.EJBJoinPointImpl.invoke(EJBJoinPointImpl.java:35)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:69)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:69)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.system.TxRequiredInterceptor.invoke(TxRequiredInterceptor.java:55)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:69)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
    06/11/16 13:12:01      at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:69)
    06/11/16 13:12:01      at com.evermind.server.ejb.StatelessSessionEJBObject.OC4J_invokeMethod(StatelessSessionEJBObject.java:86)
    06/11/16 13:12:01      at IssueHoursBean_StatelessSessionBeanWrapper0.getIssueHoursById(IssueHoursBean_StatelessSessionBeanWrapper0.java:72)
    06/11/16 13:12:01      at view.actions.IssuesAction.list(IssuesAction.java:47)
    06/11/16 13:12:01      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    then I've written q.setParameter(0, 7). it helped me to avoid above exception. but I've got another one:
    01:22:07.474--UnitOfWork(1887)--Thread(Thread[ApplicationServerThread-0,5,RequestThreadGroup])--Exception
    [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.DatabaseException
    java.sql.SQLException: ORA-01008: not all variables bound
    Error code: 1008
    Call:select * from a where type=?1
    Query:ReadAllQuery(com.desyde.tmsissue.model.ejb.entity.IssueHours)
    I've tried to modify query in such ways:
    select * from a where type=?
    select * from a where type=?0
    Have got the same exception.
    Could somebody help me?
    Thanks.

  • Named Parameters in Functions: Possible?

    I want to use named parameters to call PL/SQL functions using JDBC, as is best practice and necessary for default values to work. Unfortunatley all the examples I found are for procedures only. Using a positional registerOutParameter with named register / get methods on the CallableStatement does not work, obiviously.
    Is there any proper way to use named parameters with functions ? Proper does not include writing wrapper procedures nor turning functions into procedures.

    Hi Avi,
    as far as I know the return value of a PL/SQL function does not have a name, as oposed to the parameters of a PL/SQL function, which must have a name. One could argue that the return value of a function is called the same as the function itself. I have tried that option but it does not work.
    Unfortunatley the method OraclePreparedStatement.registerReturnParameter refers to something else than the return value of a PL/SQL function. Is it possible that the developers of the driver have forgotten something?

  • Named parameters in stored function

    Hi,
    I am trying to execute stored function from java in oracle . I am using Oracle 9.2.0.1.0 and the newest JDBC drivers, ie. for 10g which are compatible. I have flicked through JDBC Named Parameters example but it only addresses stored procedures.
    The problem I have is that I do not know what name the return value of stored procedure has.
    stored function parameter names:
    1. ????
    2. test1 Mode: IN
    3. test2 Mode: IN
    ?=call test_function(?,?);
    When I am trying to set values as indexes everything works perfect.
    CallableStatement cs = .....
    cs.registerOutParameter(1, Types.VARCHAR);
    cs.setString(2, "a");
    cs.setString(3, "b");
    cs.execute();
    String returnedValue = cs.getString(1);
    However, when I am trying to use named parameters the code looks like this:
    CallableStatement cs = .....
    cs.registerOutParameter(1, TYPES.VARCHAR);
    cs.setString("test1", "a");
    cs.setString("test2", "b");
    and the question is what is the name of return parameter.
    I have tried to put the same name as the name of stored function but is reports error.
    Instead I had to first getmetadata from oracle and in case of stored functions utilize it, unfortunatelly getting metadata has perfomance issues and I heard that oracle 10g is even slower in getting metadata.
    If anyone knows the answer to my question, please answer.
    Thank you in advance,
    Mateusz Szczap
    Java Programmer
    NCDC
    [email protected]
    http://www.ncdc.pl

    Hi,
    I am trying to execute stored function from java in oracle . I am using Oracle 9.2.0.1.0 and the newest JDBC drivers, ie. for 10g which are compatible. I have flicked through JDBC Named Parameters example but it only addresses stored procedures.
    The problem I have is that I do not know what name the return value of stored procedure has.
    stored function parameter names:
    1. ????
    2. test1 Mode: IN
    3. test2 Mode: IN
    ?=call test_function(?,?);
    When I am trying to set values as indexes everything works perfect.
    CallableStatement cs = .....
    cs.registerOutParameter(1, Types.VARCHAR);
    cs.setString(2, "a");
    cs.setString(3, "b");
    cs.execute();
    String returnedValue = cs.getString(1);
    However, when I am trying to use named parameters the code looks like this:
    CallableStatement cs = .....
    cs.registerOutParameter(1, TYPES.VARCHAR);
    cs.setString("test1", "a");
    cs.setString("test2", "b");
    and the question is what is the name of return parameter.
    I have tried to put the same name as the name of stored function but is reports error.
    Instead I had to first getmetadata from oracle and in case of stored functions utilize it, unfortunatelly getting metadata has perfomance issues and I heard that oracle 10g is even slower in getting metadata.
    If anyone knows the answer to my question, please answer.
    Thank you in advance,
    Mateusz Szczap
    Java Programmer
    NCDC
    [email protected]
    http://www.ncdc.pl

  • Optimizer not using index even after giving the hint

    Hi All,
    I am wondering why Optimixzer is not using the index in the below query
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    SQL> select column_expression
      2  from ALL_IND_EXPRESSIONS
      3  where table_name like 'GTXN_DTL_V1'
      4  and index_name = 'IDX_TXN11_V1';
    COLUMN_EXPRESSION
    TO_DATE("BOOKING_DATE",'YYYYMMDD')
    SQL> select num_rows from all_tables
      2  where table_name like 'GTXN_DTL_V1';
      NUM_ROWS
      29020867
    SQL>  explain plan for select * from gtxn_dtl_v1 where to_date(booking_date,'yyyymmdd') = to_date('030109','DDMMRR');
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3140624094
    | Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |             | 55489 |    15M|   215K  (4)| 00:43:08 |
    |*  1 |  TABLE ACCESS FULL| GTXN_DTL_V1 | 55489 |    15M|   215K  (4)| 00:43:08 |
    Predicate Information (identified by operation id):
       1 - filter(TO_DATE("BOOKING_DATE",'yyyymmdd')=TO_DATE('030109','DDMMRR
    14 rows selected.
    --Giving Hint..
    SQL> explain plan for select /*+ index(gtxn_dtl_v1 IDX_TXN11_V1) */ *
      2  from gtxn_dtl_v1
      3  where to_date(booking_date,'yyyymmdd') = to_date('030109','DDMMRR')
      4  /
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3140624094
    | Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |             | 55489 |    15M|   215K  (4)| 00:43:08 |
    |*  1 |  TABLE ACCESS FULL| GTXN_DTL_V1 | 55489 |    15M|   215K  (4)| 00:43:08 |
    Predicate Information (identified by operation id):
       1 - filter(TO_DATE("BOOKING_DATE",'yyyymmdd')=TO_DATE('030109','DDMMRR
    14 rows selected.Please suggest.
    Thanks in advance,
    Jeneesh

    porzer wrote:
    Hi!
    Why are you using the to_date ont the booking_date column? Is it a varchar2 column, what type is it.
    Because if it's a varchar2 column you could simply use
    select * from gtxn_dtl_v1 where booking_date = '20090103';
    So you wouldn't even need a function based index.
    On the other hand if it's a date you shouldn't do a to_date as well.
    Best regards,
    PPThat is not the original qury used in production. I am investigating on the prformance of the below query.
    select  txn.account_number,to_number(txn.amount_lcy) txn_amt,to_date(booking_date,'yyyymmdd') TXN_DATE,
          sal.latest_sal,sal.sal_date,customer_name,employer_name,
           decode(COMMUNICATION_TYPE_1,'MOBILE',COMMUNICATION_NO_1,decode(COMMUNICATION_TYPE_2,'MOBILE',COMMUNICATION_NO_2)) mob,
           txn.CURRENCY, CHEQUE_NUMBER,trans_dets,trans_reference,target,teller_id,acc.category,acc.inactive_marker,acc.posting_restrict,cus.sector,cus.industry
    from coreadmin.Gtxn_dtl_v1 txn,
                   (select account_number,round(to_number(nvl(amount_lcy,0)),2) latest_sal,TXN_DATE sal_date,rr
                    from
                      (select to_date(booking_date,'yyyymmdd') TXN_DATE,batch_id,account_number,amount_lcy
                             ,row_number() over (partition by account_number order by to_date(booking_date,'yyyymmdd') desc NULLS LAST,batch_id desc nulls last) rr,
                             CURRENCY, CHEQUE_NUMBER,trans_dets,trans_reference
                        from coreadmin.Gtxn_dtl_v1
                        where transaction_code = '204'
                    and to_number(amount_lcy) > 0)
                        where rr = 1
                     ) sal,customers_live cus,accounts_live acc
    where to_date(booking_date,'yyyymmdd') between to_date('030109','DDMMRR') and to_date('030209','DDMMRR')
    and txn.account_number = sal.account_number
    and txn.CUSTOMER_ID = cus.CUSTOMER_number(+)
    and acc.id = sal.account_number
    and target in ('30','31','32')Edited by: jeneesh on Mar 25, 2009 12:38 PM
    Corrected the query.
    The column is of VARCHAR2 type. This is because, the table is loaded, through sqlldr, every day from flat files generated form GLOBUS banking system. Column is kept as VARCHAR2 to minimize the loading issues.

  • Named parameters in Native SQL

    A little background first:
    Our website uses Hibernate as it's JPA provider, but we've run into several issues with it, one of which they actively refuse to fix out of pure arrogance, even when we gave them a good patch for it. The other one is a performance issue that can be greatly improved by passing arrays as parameters, which I've read rumours is supported in EclipseLink. I first tried implementing a Hibernate UserType as they've specified and it turns out they never read them into the Map that looks-up parameter types during binding, even though it's loaded from their hibernate.cfg.xml. In other words, they're only pretending to support custom user types, but unless you're writing-out the full manual loading of their configuration, there's no way to do it.
    After a day of trying to fix all the relation annotations that EclipseLink finds unacceptable in our project (which only uses native SQL and EntityManager.find for selects) I finally got it running and came to discover you don't support named parameters in native SQL. That was really disappointing, because a few months ago we migrated all our queries to named parameters, because positioning ones were too difficult to track and caused more bugs when we had to add more criterias.
    My questions are these:
    Are named parameters for native SQL not supported by JPA specifications or because they are considered low priority?
    Would you accept a patch that supports them?
    Can we really use arrays and/or lists as parameters in queries like this "SELECT * FROM some_table WHERE my_column_a IN ? AND my_column_b NOT IN ?"
    If yes to above, would it still work if the first one is an array of integers and the second is an array of strings?
    Would it work if it's in native SQL and the column types cannot be resolved due to query complexity?

    A little background first:
    Our website uses Hibernate as it's JPA provider, but we've run into several issues with it, one of which they actively refuse to fix out of pure arrogance, even when we gave them a good patch for it. The other one is a performance issue that can be greatly improved by passing arrays as parameters, which I've read rumours is supported in EclipseLink. I first tried implementing a Hibernate UserType as they've specified and it turns out they never read them into the Map that looks-up parameter types during binding, even though it's loaded from their hibernate.cfg.xml. In other words, they're only pretending to support custom user types, but unless you're writing-out the full manual loading of their configuration, there's no way to do it.
    After a day of trying to fix all the relation annotations that EclipseLink finds unacceptable in our project (which only uses native SQL and EntityManager.find for selects) I finally got it running and came to discover you don't support named parameters in native SQL. That was really disappointing, because a few months ago we migrated all our queries to named parameters, because positioning ones were too difficult to track and caused more bugs when we had to add more criterias.
    My questions are these:
    Are named parameters for native SQL not supported by JPA specifications or because they are considered low priority?
    Would you accept a patch that supports them?
    Can we really use arrays and/or lists as parameters in queries like this "SELECT * FROM some_table WHERE my_column_a IN ? AND my_column_b NOT IN ?"
    If yes to above, would it still work if the first one is an array of integers and the second is an array of strings?
    Would it work if it's in native SQL and the column types cannot be resolved due to query complexity?

  • Named Query or Native Query

    Hello,
    I am using native query to search for results on my search page. A friend of mine just told me that I better use named query or the time to get my search results will be too slow.
    Does Named Query give you faster result than Native Query?
    Thanks in advance.
    Regards,
    Hemen

    When you define named queries (note that this is a Hibernate example) you can put them in for example XML,
    <query name="findItemsByDescription">
    <![CDATA[from Item item where item.description like :desc]]>
    </query>or a SQL query like
    <sql-query name="findItemsByDescription">
    <return alias="item" class="Item"/>
    <![CDATA[select {item.*} from item where description like :desc]]>
    </sql-query>You can call these queries by using the same code, for example,
    session.getNamedQuery("findItemsByDescription").setString("desc", description);This is what is being meant by sharing the same calling API.
    When taking about performance. You have to know something about what goes on under the hood.
    You have probably programmed something using straightforward JDBC, so you know how to queries
    get passed to the driver and send to the database. When using HQL or JPA-QL the queries first have
    to be parsed into an SQL language that the database can understand. In this case, we have an extra
    parsing step in between. Note that Native SQL queries, including stored procedure calls, the persistence
    framework still takes care of mapping the JDBC result sets to graphs of persistent objects.
    If you want to include a native SQL hint to instruct the database management systems query optimizer,
    for example, you need to write the SQL yourself. HQL and JPA-QL do not have keywords for this.
    The disadvantage of putting native SQL in your mapping metadata is lost database portability, because
    your mappings, and hence your application, will work only for a particular database. But usually this is of a
    minor concern as you are probably not creating a framework that has to work on every database.
    When you want to get behind the performance of your query, you really have to consult the database
    and look at the execution plan - A DBA can tell you exactly what is good and what can be optimized.

  • How to create olap cube using Named Query Table in Data source View

     I Create on OLAP Cube using Existing Tables Its Working Fine But When i Use Named Query Table with RelationShip To other Named query Table  It Not Working .So give me some deep Clarification On Olap Cube for Better Understanding
    Thanks

    Hi Pawan,
    What do you mean "It Not Working"? As Kamath said, please post the detail error message, so that we can make further analysis.
    In the Data Source View of a CUBE, we can define a named query. In a named query, you can specify an SQL expression to select rows and columns returned from one or more tables in one or more data sources. A named query is like any other table in a data source
    view (DSV) with rows and relationships, except that the named query is based on an expression.
    Reference:Define Named Queries in a Data Source View (Analysis Services)
    Regards,
    Charlie Liao
    TechNet Community Support

  • Query on virtual column that is defined in XMLIndex does not use the index

    Hello,
    I am facing an issue in executing queries on a virtual column that is defined in an XMLIndex: it appears as if the index is not used.
    Database details:
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE 11.2.0.3.0 Production
    TNS for 64-bit Windows: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    For this use case the XML documents adhere to the following XSD and are stored in an XMLType column in a table:
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns="http://a_name_space/v1"
        targetNamespace="http://a_name_space/v1"
        elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0">
        <xsd:element name="fields">
            <xsd:complexType>
                <xsd:sequence>
                    <xsd:element name="field" maxOccurs="unbounded">
                        <xsd:complexType>
                            <xsd:choice>
                                <xsd:element name="value" minOccurs="1" maxOccurs="1">
                                    <xsd:complexType>
                                        <xsd:simpleContent>
                                            <xsd:extension base="notEmptyString4000Type"/>
                                        </xsd:simpleContent>
                                    </xsd:complexType>
                                </xsd:element>
                                <xsd:element name="values" minOccurs="1" maxOccurs="1">
                                    <xsd:complexType>
                                        <xsd:sequence>
                                            <xsd:element name="value" minOccurs="1" maxOccurs="1">
                                                <xsd:complexType>
                                                    <xsd:simpleContent>
                                                        <xsd:extension base="notEmptyString4000Type">
                                                            <xsd:attribute name="startDate" type="xsd:date" use="required"/>
                                                            <xsd:attribute name="endDate" type="xsd:date" />
                                                        </xsd:extension>
                                                    </xsd:simpleContent>
                                                </xsd:complexType>
                                            </xsd:element>
                                        </xsd:sequence>
                                    </xsd:complexType>
                                </xsd:element>
                            </xsd:choice>
                            <xsd:attribute name="name" type="string30Type" use="required"/>
                            <xsd:attribute name="type" type="dataType" use="required"/>
                        </xsd:complexType>
                    </xsd:element>
                </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
        <xsd:simpleType name="dataType">
            <xsd:annotation>
                <xsd:documentation>Char, Date, Number</xsd:documentation>
            </xsd:annotation>
            <xsd:restriction base="xsd:string">
                <xsd:enumeration value="C"/>
                <xsd:enumeration value="D"/>
                <xsd:enumeration value="N"/>
            </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="string30Type">
            <xsd:restriction base="xsd:string">
                <xsd:maxLength value="30"/>
            </xsd:restriction>
        </xsd:simpleType>
        <xsd:simpleType name="notEmptyString4000Type">
            <xsd:restriction base="xsd:string">
                <xsd:maxLength value="4000"/>
                <xsd:pattern value=".+"/>
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:schema>A field can have a single value as well as multiple values.
    The XMLIndex is defined as follows:
    CREATE INDEX test_xmltype_idx ON test_xmltype (additional_fields) INDEXTYPE IS XDB.XMLIndex
    PARAMETERS
    XMLTable dt_fld_tab (TABLESPACE "TAB_SPACE" COMPRESS FOR OLTP) ''fields/field''
    COLUMNS
    name varchar2(30 char) PATH ''@name''
    ,dataType varchar2(1 char) PATH ''@type''
    ,val varchar2(4000 char) PATH ''value/text()''
    ,vals XMLType PATH ''values/value'' VIRTUAL
    XMLTable dt_fld_multi_value_tab (TABLESPACE "TAB_SPACE" COMPRESS FOR OLTP) ''value'' passing vals
    COLUMNS
    val varchar2(4000) PATH ''text()''
    ,startDate varchar2(30 char) PATH ''@startDate''
    ,endDate varchar2(30 char) PATH ''@endDate''
    ');The following b-tree indexes are defined:
    create index dt_field_name_idx on dt_fld_tab (name);
    create index dt_field_value_idx on dt_fld_tab (val);
    create index dt_field_values_idx on dt_fld_multi_value_tab (val);And stats are properly computed before the queries are executed:
    call dbms_stats.gather_table_stats(user, 'test_xmltype', estimate_percent => null);Queries for single values are cost efficient and fast. With 600K rows in the table these return with 0.002 seconds.
    Queries for multi-valued fields / elements are not though, these result in a full table scan.
    Sample XML snippet:
    <fields>
      <field name="multiVal" type="C">
        <values>
          <value startDate="2013-01-01" endDate="2013-01-01">100</value>
          <value startDate="2014-01-01">120</value>
        </values>
      </field>
    </fields>Examples of costly and slow queries:
    select id from test_xmltype
    where xmlexists('/fields/field/@name="multiVal"' passing additional_fields)
    and xmlexists('/fields/field/values/value[@startDate="2013-01-01"]' passing additional_fields)
    and xmlexists('/fields/field/values/value[text()="100"]' passing additional_fields)
    select id from test_xmltype
    where xmlexists('/fields/field/@name="multiVal"' passing additional_fields)
    and xmlexists('/fields/field/values/value[@startDate="2013-01-01" and .="100"]' passing additional_fields);Whereas the following query on the multi valued field is fast:
    select id from test_xmltype
    where xmlexists('/fields/field/@name="multiVal"' passing additional_fields)
    and xmlexists('/fields/field/values/value[@startDate="2013-01-01"]' passing additional_fields);For the XPath /fields/field/values/value[@startDate="2013-01-01"] the index is used.
    Suspected cause: XPath issue for the value of a multi valued field, e.g. /fields/field/values/value[text()="aValue"].
    Any hints are appreciated: what am I overlooking here?
    Thanks in advance,
    -Sjoerd
    Edited by: user615230 on May 27, 2013 7:46 AM

    Hello,
    This is using binary XML. The table creation script is:
    create table test_xmltype
    (id number(14,0) not null primary key
    ,member_code varchar2(30 char) not null
    ,period_code varchar2(30 char) not null
    ,amount number(12,2) not null
    ,additional_fields xmltype
    );The schema is not registered in the database. Is that required? It is primarily used to generate Java classes that will be used in order to construct the XML documents.
    And you are right: for our initial investigation the sample XML documents are generated with a PLSQL routine and do not contain namespaces. But for the single valued fields there are also no namespaces and the queries on these are executed with very satisfactory plans.
    Thanks for the swift reply.
    -Sjoerd

  • Do Not Use SOAP Envelope doesn't show on SOAP Parameters

    Hi!..
    Somebody knows why the Do Not Use SOAP Envelope option on conversion Parameters for SOAP Adapter isn't there?...I have XI 3.0 SP19 and I'd seen on a lot of notes and how's to that there is a kind of option. I need the functionality that that check does but I can't find it.
    I Only have Keep headers, Keep Attachments, Use Encoded headers and Use query string.
    Thanks in advance..
    Carlos.

    HI Carlos,
    I've got same problem, which metadata should I reimport?
    cheers,
    Edu

Maybe you are looking for

  • Authentication - same account name on 2 LDAP servers

    We have our mac clients set up to authenticate against 2 LDAP servers, one Open Directory, one eDirectory - to keep things easy for our users I want to use the same login username for both OD and eDirecotry users - we basically have users logging int

  • HOW TO IMPORT PRICE LIST?

    Dear friends. i am facing problem in importing price list,can u plz help me. 1)i have made price list for certen items , that is ok with factor 1 2)now i wants to update this price list through DTW 3)but as per SAP templete i am anable to update it.

  • Web-based Chiness Chess Game Application(24-11-02007 OPEN)

    The following is access link: http://carltam.no-ip.info:8083/Game/showLogin.html The game is a turn-based one and is implemented on using server/multi-client model(server program, applet) Technology used: signed applet, multi-threading, socket, objec

  • How to e-mail?

    Hey! How can I e-mail to Nokia firmware developers? Pls help me! Thanks Paul!

  • Cluster setup problem

              If I have two boxes, with static IP: 192.168.21.5 (box A) and .6 (box B). How would           I setup the cluster?           Specifically, if I make admin Admin at 192.168.21.5:7001, Managed-1 at 192.168.21.5:7101           and Managed-2 at