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.

Similar Messages

  • Differences between Native Query and Hibernate Native Query?

    What is the differences between this two queries? as i was looking for native query. i saw hibernate native query... from what i've search through the internet, i know noted that hibernate query and native query is a totally different queries
    so is hibernate native query belongs to hibernate query? i m quite confuse 2 differentiate this with native query

    hi,
    Information is retrieved from the data base for use in out programs via a special language known as structured query language (SQL). SQL is a language designed for the use with relational data base systems.
       Open SQL is a subset of native SQL . SQL has been divided into two parts.
    > Open SQL  can recognized by the ABAP program.
    > They are 10 SQL statements out of which we use only 5.
    1. Select.
    2. Insert.
    3. Delete.
    4. Modify.
    5. Update.
    6. Fetch.
    7. Open Cursor.
    8. Close Cursor.
    9. Roll Back.
    10. Commit.
    out of which we use only the first 5.....
    > Native SQL. cannot be recognized by the ABAP program.
    > To execute Native SQL
    Exec SQL.
    End Exec.
    as it cannot be recognized by the ABAP we go for Open SQL.
    If this has helped u solve ur problem then dont forget to reward them with pointrs.
    with regards,
    madhuri.

  • 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!

  • Issue in running GTC having Customized & native query

    Hi Experts,
    We are creating "OIM 9.1 - OIM11g SYNC GTC". When Scheduled task is run, this GTC should be updating the records of OIM11g by taking the data from OIM 9.1 DB.
    We have used the following connection parameters:
    Specify Parameter Values Change
    Database Driver oracle.jdbc.driver.OracleDriver
    Database URL jdbc:oracle:thin:@***************:1521:oimusdb
    Database User ID oimdev
    Database Password ********
    Customized Query (USRIMPORT.USR_EMP_TYPE='Employee' or USRIMPORT.USR_EMP_TYPE='Contractor') and USRIMPORT.USR_STATUS<>'Deleted'
    Use Native Query Yes
    Connection Properties
    Parent Table/View Name USRIMPORT
    Child Table/View Names
    Unique Attribute USR_KEY
    Timestamp Attribute USR_CREATED
    Database Date format
    Batch Size All
    Stop Reconciliation Threshold None
    Stop Threshold Minimum Records None
    Source Date Format yyyy/MM/dd HH:mm:ss z
    Reconcile Deletion of Multivalued Attribute Data No
    Reconciliation Type Incremental
    While running the GTC we are getting following error in logs:
    [XELLERATE.GC.FRAMEWORKRECONCILIATION] [tid: OIMQuartzScheduler_Worker-4] [userId: oiminternal] [ecid: 0000JIbnbxk7u1ADrb4ioY1F10jR000002,0] [APP: oim#11.1.1.3.0] Reconciliation Encountered error: [[
    com.thortech.xl.gc.exception.ProviderException: For non-native customized query, please use & for AND and | for OR.
    at com.thortech.xl.gc.impl.recon.DBReconTransportProvider.getCustomizedQueryCondition(Unknown Source)
    For resolving the above issue, we have tried following combinations: (WHICH ARE NOT WORKING TILL NOW)
    1. Scenario 1:
    query: (USRIMPORT.USR_EMP_TYPE='Employee' | USRIMPORT.USR_EMP_TYPE='Contractor') & (USRIMPORT.USR_STATUS='Disabled' | 'USRIMPORT.USR_STATUS='Active')
    USE NATIVE QUERY = 'NO'
    ERROR: [XELLERATE.GC.FRAMEWORKRECONCILIATION] [tid: OIMQuartzScheduler_Worker-4] [userId: oiminternal] [ecid: 0000JIbnbxk7u1ADrb4ioY1F10jR000002,0] [APP: oim#11.1.1.3.0] Reconciliation Encountered error: [[
    com.thortech.xl.gc.exception.ProviderException: For non-native customized query, please use & for AND and | for OR.
    at com.thortech.xl.gc.impl.recon.DBReconTransportProvider.getCustomizedQueryCondition(Unknown Source)
    2. Scenario 2:
    query- (USRIMPORT.USR_EMP_TYPE='Employee' OR USRIMPORT.USR_EMP_TYPE='Contractor') AND (USRIMPORT.USR_STATUS='Disabled' OR 'USRIMPORT.USR_STATUS='Active')
    USE NATIVE QUERY ='yes'
    ERROR:
    class/Method: DBFacade/getRecord encounter some problems: ORA-00920: invalid relational operator[[
    java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational operator
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:457)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:405)
    3. Scenario 3:
    query- (USRIMPORT.USR_EMP_TYPE='Employee' OR USRIMPORT.USR_EMP_TYPE='Contractor') AND (USRIMPORT.USR_STATUS='Disabled' OR 'USRIMPORT.USR_STATUS='Active')
    USE NATIVE QUERY='NO'
    ERROR:
    ERROR] [] [XELLERATE.GC.FRAMEWORKRECONCILIATION] [tid: OIMQuartzScheduler_Worker-6] [userId: oiminternal] [ecid: 0000JIbnbxk7u1ADrb4ioY1F10jR000002,0] [APP: oim#11.1.1.3.0] Reconciliation Encountered error: [[
    com.thortech.xl.gc.exception.ProviderException: For non-native customized query, please use & for AND and | for OR.
    at com.thortech.xl.gc.impl.recon.DBReconTransportProvider.getCustomizedQueryCondition(Unknown Source)
    at com.thortech.xl.gc.impl.recon.DBReconTransportProvider.getQueryCondition(Unknown Source)
    at com.thortech.xl.gc.impl.recon.DBReconTransportProvider.getFirstPage(Unknown Source)
    Please guide me on the same.

    Hi,
    Thanks for this but i have done as per this document. while running i came to know that there are 2 executable programs in the same name. so i need to remove the one executable program then i run this concurrent program to confirm it. that really we achieved it or not.
    Awaiting for your reply
    Thanks
    M.K.Thamaraiselvan.

  • Aggregate function in native query (EJB 3.0)

    How do you run a aggregate function in a native query? I have a particular use case, for reporting purposes, where the result set is too large to fetch the actual CMP collection, thus I need to execute a native count/avg select. I want some thing like,
    Integer totalRecords = (Integer)
           em.createNativeQuery("select count(*) from records").getSingleResult();

    Oracle is intelligent enough to use index only if query result filtering is based on it and result set is less than 5% of the total data set.Sorry to be blunt but that 5% stuff is nonsense.
    Here since the index column is not used in the WHERE clause, oracle performs full table scan.That's not true either. Under the right circumstances the optimizer can use the index, even without a WHERE clause in the query:
    SQL> create table t as select * from dba_objects where object_type is not null;
    Table created.
    SQL> alter table t modify object_type not null;
    Table altered.
    SQL> create index t_idx on t(object_type);
    Index created.
    SQL> explain plan for
      2  select object_type, count(*) from t group by object_type;
    Explained.
    | Id  | Operation             | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |       |    44 |   396 |    60   (7)| 00:00:01 |
    |   1 |  HASH GROUP BY        |       |    44 |   396 |    60   (7)| 00:00:01 |
    |   2 |   INDEX FAST FULL SCAN| T_IDX | 72474 |   636K|    57   (2)| 00:00:01 |
    -------------------------------------------------------------------------------With the OP's query, it (apparently) can not be satisfied by using only the index.
    WHERE TO_CHAR(COL) = TO_CHAR(COL)I don't even know what this means. Usually if you perform a function on an indexed column, the optimizer will not use the index (unless of course it's an fbi).

  • 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.

  • ORA-00932 in Native Query

    Hello.
    I'm using some native queries in my EJB 3.0 project.
    When I write a native query like
    INSERT INTO SOME_TABLE VALUES (:val0, :val1, :val2) and use the executeUpdate() method of the Query interface after assigning all parameters to values other than null everything works OK.
    However, if I let any of the values be null (even though that exactly what I want to put in the database) I get the following exception:
    java.sql.SQLException: ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
    Is there any way to go arround this? I really must write the nulls to the database.
    Thanks in advance,
    Hugo Oliveira
    [email protected]

    Do you mean writing a query like
    "INSERT INTO SOME TABLES VALUES :val0, NULL, :val2"
    instead of
    "INSERT INTO SOME TABLES VALUES :val0, :val1, :val2"
    where the val1 parameter would be assigned a null variable, or passing a null directly in setParameter (query.setParameter("val1", null)) instead of a null variable (query.setParameter("val1", nulVar))?
    Hugo Oliveira
    [email protected]

  • Change Existing objects naming conventions in a Query

    Hi all,
    I Need to change the Naming Conventions of the Query Objects of a Query at the Infoprovider level. Is there any Routine to change the naming conventions or do i need to do it Manually.

    Hi gopinath,
    mine is also a similar case, the problem with the option u gave me is that our implementation is in EDW environment and rework from the scratch is not an option for me. Is it possible to change the query objects naming convention at particular info-provider level, i have about 200 objects created with random naming convention and to be now changed according to a standard naming convention. I need to also consider how the changes effect other queries and reports as well.. So is there any possible way of Custom coding a routine or a program that can solve my purpose.. has any one gone through the same situation?
    thanks,
    kishore

  • JPA  using native query - distinct

    Hi All,
    Kindly suggest on the following,
    I am facing issues on using the distinct keyword in JPA, Ful details on the following OTN thread.
    JPA  using native query - distinct
    Any help is much appreciated
    VR

    Any ideas ?

  • Suppress Power Query's Native Database Query Warning

    Is there a way to suppress the "Native Database Query" warning issued by Power Query when running a SQL query directly against a Teradata database?  This warning states, "You are about to run a native database query.  Native queries
    can make changes to the database.  Would you like to run the following query?"

    If we never prompted here, then I could send you a workbook with the embedded query "drop table foo". You'd open it, Power Query would run analysis and we'd execute the statement -- all before you had any idea what had happened. It's true that
    there are many potential users for whom showing the SQL text isn't useful. Hopefully, those users don't have the kinds of server permission that would let a query run with their credentials do lasting damage. But the prompt is to deal with the very possible
    risk of having even a sophisticated user run a query by accident that they shouldn't have.
    The original intent of the feature was to support a scenario where a user says "I already have a SQL query whose output I want to consume into Power Query; why can't I just use that?" It did not take parameterization into account. We subsequently
    considered adding parameterization to this method, but didn't feel that we could sufficiently guarantee security. That is, if your query text is Sql.Database("server", "database", [Query="exec @sql", Parameters=[sql="drop
    table foo"]], the user would be prompted only with "exec @sql" and the malicious payload would be delivered invisibly.
    We very much do not want to have the responsibility of parsing multiple different dialects of SQL to try to guess whether or not it contains potentially-malicious code.
    Our current thinking on this is that we might let advanced users write "trusted code" which has to go through a separate verification step. Code of this type might be able to generate SQL statements without a user prompt. So a workbook might have
    a dependency on the "My Trusted Code" module, and simply won't run if that module hasn't been installed on the local machine. The user would then need a trustworthy (but convenient) way to obtain that module from a trustworthy source.

  • Incremental variable in column native query

    i'm looking for a jpql way of doing a cumulative variable query like subttl:
    select scat.*, @subttl:=if(@subttl=null,0,@subttl) +imp*dh as subttl from scat;is there any way to use variables in the select clause ?...
    As other way, I thought making a native query but I need the resultset mapped to an entity bean, so I think it can't be possible.
    I appreciate your help!!

    Hi sebatxtz!
    You can always use SqlResultSetMappings to map the result of a native query to entities.
    [http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#SqlResultSetMapping|http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#SqlResultSetMapping]
    As for your original problem, sorry I'm not that big of a jpql expert. :(
    -Zsom-

  • Confusion over Native Query Result List

    I have this confusion over the field object of a resultList of a Native query. This is because it has contradicted the idea of the books for me.
    This is a pure example
    @SqlResultSetMapping(name="LoanCapitalization.reportMapping",
    columns={
        @ColumnResult(name="policy_number"),
        @ColumnResult(name="policy_holder"),
        @ColumnResult(name="amount"),
        @ColumnResult(name="outstanding_loan"),
        @ColumnResult(name="interest"),
        @ColumnResult(name="amount_to_date"),
        @ColumnResult(name="effective_date"),
        @ColumnResult(name="sub_system_code")
    @NamedNativeQuery(name="LoanCapitalization.aggregateStatement", query="SELECT   l.policy_number, l.last_name || ' ' || l.first_name as " +
            "policy_holder, l.amount, c.out_principal_bf as outstanding_loan, c.out_interest_bf as interest, " +
            "SUM (r.repayment_amount) as amount_to_date, c.effective_date, l.sub_system_code FROM loan l JOIN v_latest_capitalization c " +
            "ON l.loan_id = c.loan_id JOIN loan_repayment r ON l.loan_id = r.loan_id WHERE " +
            "c.effective_date BETWEEN ?1 AND ?2 GROUP BY l.policy_number, l.last_name, l.first_name, l.amount, " +
            "c.out_principal_bf, c.out_interest_bf, c.effective_date, l.sub_system_code order by l.sub_system_code, l.last_name",
            resultSetMapping="LoanCapitalization.reportMapping")and
    Query query = entityManager.createNamedQuery("LoanCapitalization.aggregateStatement");
            AggregateStatementLoanBalanceReportData data = null;
            List<AggregateStatementLoanBalanceReportData> returnList = new ArrayList<AggregateStatementLoanBalanceReportData>();
            query.setParameter(1, reportCriteria.getFromDate());
            query.setParameter(2, reportCriteria.getToDate());
            List<Object[]> resultList = query.getResultList();
            System.out.println("resultList.size() >>>>>>>>>> " + resultList.size());
            for (Object[] obj : resultList){
                data = new AggregateStatementLoanBalanceReportData();
                System.out.println("(String)obj[1] >>>>>>>>>> " + (String)obj[1]);
                System.out.println("(String)obj[2] >>>>>>>>>> " + (String)obj[2]);
                System.out.println("(String)obj[3] >>>>>>>>>> " + (String)obj[3]);
                System.out.println("(String)obj[4] >>>>>>>>>> " + (String)obj[4]);
                System.out.println("(String)obj[5] >>>>>>>>>> " + (String)obj[5]);
                System.out.println("(String)obj[6] >>>>>>>>>> " + (String)obj[6]);
                data.setPolicyNumber((String)obj[0]);
                data.setName((String)obj[1]);
    .......My first shocking surpise is that all the System.out.println() return nulls but
    System.out.println("resultList.size() >>>>>>>>>> " + resultList.size()); returned 1.
    so can anyone suggest what the problem may be.
    Regards,
    Michael

    I came across your post as I experienced the same problem. As I found no answers I tried different let's say stupid solutions.
    The one that solved my problem was to write the name for the @ColumnResult in capitals as I noticed that Oracle transforms the alias column names into capitals. I guess otherwise the mapping doesn't occur correctly.
    My example:
    @SqlResultSetMappings({
    @SqlResultSetMapping(
    name = "Customers.searchCustomers",
    entities =
    @EntityResult(entityClass = Customers.class)
    columns =
    @ColumnResult(name = "CONTACTDATE"),
    @ColumnResult(name = "CONTRACTDATE")
    String queryString =
    "SELECT c.CUSTOMER_ID, c.LAST_NAME, c.FIRST_NAME, c.OPU, c.CUSTOMER_CORE_ID, " +
    "to_char(con.CONTACT_DATE, 'yyyy-dd-mm') AS CONTACTDATE, to_char(contr.CONTRACT_DATE, 'yyyy-dd-mm') AS CONTRACTDATE " +
    "FROM CUSTOMERS c " +
    "LEFT JOIN CONTACTS con ON con.CUSTOMER_ID = c.CUSTOMER_ID AND con.ACTIVE = '1' " +
    "LEFT JOIN CONTRACTS contr ON contr.CUSTOMER_ID = c.CUSTOMER_ID AND contr.ACTIVE = '1' " +
    "WHERE c.CAMPAIGN_ID = ?1 AND upper(c.LAST_NAME) LIKE ?2 AND upper(c.FIRST_NAME) LIKE ?3";
    query = em.createNativeQuery(queryString,
    "Customers.searchCustomers");

  • Jpa native query returns only first character of a field

    Hi,
    I've a JPA native query that returns two fields from my oracle database. The first field is a CHAR(2) field with two char values in it, like 'OZ' etc.
    The problem is, as soon as the query is executed it returns only first character of field1. If the actual value of field1 is like 'OZ' then it returns only 'Z'.
    Query nativeQueryForProfileInfo = getManager().createNativeQuery(queryToRun);
    List list = nativeQueryForProfileInfo.getResultList();
    Please help,
    thanks

    There could be several explanations here and it's difficult to say without having more details, possibilities are
    There is something wrong with your display logic.
    There is something wrong with your mapping.

  • Can't read with native query a type of CHAR(2)

    I'm working with mysql 5 /EJB3/JDK6
    I want from a nativequery read a field of CHAR(n) in a database, when I user varchar , it s works, but if i use char(n), I always get a java.lang.Character instead of a String.
    CREATE TABLE testchar(
    myid CHAR(2) PRIMARY KEY
    )When i user native query to retrive data then I get a java.lang.Character instead of a String.
    q=em.createNativeQuery("SELECT myid FROM testchar");
    q.setMaxResults(2);
    List<Object[]> r= q.getResultList();
    log.info("class="+ r.get(0).getClass()+" "+r.get(0));
    -->return java.lang.Character and value is the first character of the row     There is someone who have an idea of what is wrong?
    Thanks

    the fact that you are using a native query is the first thing that is wrong. The only time you need a native query is when you want to do something database specific. IF you do something database specific, I hope you have thought deep and hard about really needing it.

  • Using Native Query to run a SQL statement, the "getResultList" throws excep

    I run the following code and I get an exception, can someone tell me what I'm doing wrong? I tried debugging, but as soon as I try even stepping into the "getResultList" line, it throws the exception.
    public void setData(EntityManager emgr) {
    System.err.println(m_sqlStatement);
    Query q = emgr.createNativeQuery(m_sqlStatement);
    @SuppressWarnings("unchecked")
    List<List<Object>> c = q.getResultList();
    for (List<Object> d : c) {
    if (d == null || d.isEmpty()) {
    continue;
    addRow(d.toArray());
    }I took this sql statement and created a test view and ran it against my database and I get the data that I want the way that I want it. So, I feel pretty confident that the problem is not with my sql statement.
    m_sqlStatement =
    SELECT TimeSubmitted AS "Time Completed", ActivityName AS "Activity", PN AS "Part Number", OpNum AS "Op Num", isConforming AS "Conforming?", SetupHrs AS "Expected Setup Time (Hrs.)", RunHrs AS "Expected Run Time (Hrs.)" FROM CellManager INNER JOIN Routings ON Routings.ID=CellManager.RoutingsRef INNER JOIN PNTable ON PNTable.ID=Routings.PNRef INNER JOIN ActivityType ON ActivityType.ID=CellManager.ActivityTypeRef INNER JOIN Activity ON Activity.CellManagerRef=CellManager.ID WHERE CellManager.OperatorLogRef=15 Order BY TimeSubmitted
    Exception thrown:
    SEVERE: Application class productionefficiencyviewergui.ProductionEfficiencyViewerGUIApp failed to launch
    Local Exception Stack:
    Exception [TOPLINK-6132] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: Query argument " not found in list of parameters provided during query execution.
    Query: DataReadQuery(){code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I run the following code and I get an exception, can someone tell me what I'm doing wrong? I tried debugging, but as soon as I try even stepping into the "getResultList" line, it throws the exception.
    public void setData(EntityManager emgr) {
    System.err.println(m_sqlStatement);
    Query q = emgr.createNativeQuery(m_sqlStatement);
    @SuppressWarnings("unchecked")
    List<List<Object>> c = q.getResultList();
    for (List<Object> d : c) {
    if (d == null || d.isEmpty()) {
    continue;
    addRow(d.toArray());
    }I took this sql statement and created a test view and ran it against my database and I get the data that I want the way that I want it. So, I feel pretty confident that the problem is not with my sql statement.
    m_sqlStatement =
    SELECT TimeSubmitted AS "Time Completed", ActivityName AS "Activity", PN AS "Part Number", OpNum AS "Op Num", isConforming AS "Conforming?", SetupHrs AS "Expected Setup Time (Hrs.)", RunHrs AS "Expected Run Time (Hrs.)" FROM CellManager INNER JOIN Routings ON Routings.ID=CellManager.RoutingsRef INNER JOIN PNTable ON PNTable.ID=Routings.PNRef INNER JOIN ActivityType ON ActivityType.ID=CellManager.ActivityTypeRef INNER JOIN Activity ON Activity.CellManagerRef=CellManager.ID WHERE CellManager.OperatorLogRef=15 Order BY TimeSubmitted
    Exception thrown:
    SEVERE: Application class productionefficiencyviewergui.ProductionEfficiencyViewerGUIApp failed to launch
    Local Exception Stack:
    Exception [TOPLINK-6132] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: Query argument " not found in list of parameters provided during query execution.
    Query: DataReadQuery(){code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • JBO-27020

    I�m developing an application using Jdeveloper 9.0.3 (database 9.2.0.4, client Windows 2000 Professional). The view and update screens r working properly. However, when i�m running the create screen (the table uses a sequence-in-parent, with no maste

  • Error setting property in bean of type null

    Hi i have jsf page and input text a managed bean with property sum of type float i attached this property to the input text: <h:inputText id="adr" value="#{userBean.sum}"/> but when enter a value and submit the page it prints me error in the page: Er

  • How do I delete a row in Microsoft Access from a vi using the database toolkit

    Using the database toolkit 1.01 how can I delete a row from my vi

  • Database connectivity with MS Acess using WSAD5.1

    I am using WSAD5.1 as IDE and development tool. I am trying to connect to MS Access database using following lines of code Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //.newInstance(); dbConnection = DriverManager.getConnection("jdbc:odbc:DRIVER={

  • About log4j and java

    I have following code in log4j, but after execution I am unable to find file "resultFil" anywhere. appender name="resultFile" class="org.apache.log4j.RollingFileAppender"> <param name="file" value="result.log"/> <param name="MaxFileSize" value="100KB