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 ?
Similar Messages
-
Problems using native query in Active Directory connector v 9.1
Hello,
Has anyone ran into a problem when trying to do a query with a not operator?
I want to import all users, but not computers.. so I tried the query (&(objectClass=user)(!objectclass=computer))
I tried this query directly in the active directory and it worked.
The problem is when I apply it to OIM it gives out the following error:
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],ActiveDirectoryRecon::performReconciliation() Enter
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],ActiveDirectoryRecon::setTaskSchedulerObjectName() Enter
INFO,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],Starting Active Directory Trusted Reconciliation
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],ActiveDirectoryRecon::setTaskSchedulerObjectName() Exit
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],ADLookupMaps::getADFieldsArray() Enter
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],ADLookupMaps::getADFieldsArray() Exit
DEBUG,29 Oct 2008 19:48:06,337,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Enter
DEBUG,29 Oct 2008 19:48:06,350,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Exit
DEBUG,29 Oct 2008 19:48:06,350,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Enter
DEBUG,29 Oct 2008 19:48:06,363,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Exit
DEBUG,29 Oct 2008 19:48:06,363,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Enter
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcUtilAttributeNameMap::getLookupDecodeValue() Exit
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],ADReconTaskAttrs::parseAndSetMultiValAttrs() Enter
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],ADReconTaskAttrs::parseAndSetMultiValAttrs() Exit
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],ActiveDirectoryRecon/performReconciliation :query (&(&(objectClass=user)(!objectclass=computer))(whenChanged>=19000101000000.0Z))
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcADUtilLDAPController::searchResultPageEnum() Enter
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcADUtilLDAPController::connectToAvailableAD() Enter
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcADUtilLDAPController::hashTableEnvForDirContext() Enter
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcADUtilLDAPController::hashTableEnvForDirContext() Exit
DEBUG,29 Oct 2008 19:48:06,374,[OIMCP.ADCS],tcADUtilLDAPController::hashTableEnvForLDAPContext() Enter
DEBUG,29 Oct 2008 19:48:06,375,[OIMCP.ADCS],tcADUtilLDAPController::hashTableEnvForLDAPContext() Exit
DEBUG,29 Oct 2008 19:48:06,375,[OIMCP.ADCS],tcADUtilLDAPController::validateCertificates() Enter
DEBUG,29 Oct 2008 19:48:06,375,[OIMCP.ADCS],tcADUtilLDAPController::validateCertificates() Exit
DEBUG,29 Oct 2008 19:48:06,375,[OIMCP.ADCS],Critical Extensions Supported
DEBUG,29 Oct 2008 19:48:06,375,[OIMCP.ADCS],tcADUtilLDAPController::invalidateSSLSession() Enter
DEBUG,29 Oct 2008 19:48:06,549,[OIMCP.ADCS],tcADUtilLDAPController::invalidateSSLSession() Exit
DEBUG,29 Oct 2008 19:48:06,989,[OIMCP.ADCS],tcADUtilLDAPController::connectToAvailableAD() Exit
ERROR,29 Oct 2008 19:48:06,989,[OIMCP.ADCS],The error occured in tcADUtilLDAPController::searchResultPageEnum():Unbalanced parenthesis
DEBUG,29 Oct 2008 19:48:06,989,[OIMCP.ADCS],tcADUtilLDAPController::disconnect() Enter
DEBUG,29 Oct 2008 19:48:06,990,[OIMCP.ADCS],tcADUtilLDAPController::disconnect() Exit
DEBUG,29 Oct 2008 19:48:06,990,[OIMCP.ADCS],tcADUtilLDAPController::searchResultPageEnum() Exit
DEBUG,29 Oct 2008 19:48:06,990,[OIMCP.ADCS],ActiveDirectoryRecon::performReconciliation() Exit
INFO,29 Oct 2008 19:48:06,990,[OIMCP.ADCS],End of Active Directory Reconciliation....
DEBUG,29 Oct 2008 19:48:06,990,[OIMCP.ADCS],ActiveDirectoryReconTask/execute End
Thanks in advance,
TomicHi,
Try this and it will work.I am using it.
(&(objectClass=user)(!(objectClass=computer)))
Regards
Nitesh -
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} -
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,
HemenWhen 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. -
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. -
How to define a JPA "Entity" used to query multiple database tables
While using JPA to access database, I have a need to define a generic "Entity" class to use for query different tables. The reason is I have a lot of non-business tables (reference tables) I need to query. I intend to use Native SQL to do the query. Most query will only return 1 - 3 columns. It is tedious to define many JPA entities only to use them sparsely.
For example, if I have two Native query, and define a JavaBean that has 3 properties, how do I implement this in JPA?
Thanks for your help.
query 1:
select LASTNAME as f1, AGE as f2 from PERSON
query 2:
select zipcode as f1 from LOCATION
package model.uti;
public class SimpleBean {
private String f1;
private String f2;
private String f3;
public SimpleBean() {
public void setF1(String f1) {
this.f1 = f1;
public String getF1() {
return f1;
public void setF2(String f2) {
this.f2 = f2;
public String getF2() {
return f2;
public void setF3(String f3) {
this.f3 = f3;
public String getF3() {
return f3;
}An @Entity is mapped to a specific table. You can't fill it with totally random data from a collection of tables.
If you want to access data from multiple tables within the one entity, then the JPA spec defines an annotation @SecondaryTable, which allows you to specify a
second table and the join condition.
http://java.sun.com/javaee/5/docs/api/javax/persistence/SecondaryTable.html
The JPA spec talks about this as do most good EJB/JPA books.
-steve- -
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,
thanksThere 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. -
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- -
How to use Native SQL statement in JDBC receiver interface
Dear All,
Can any one please help us in using Native SQL statement in a JDBC receiver channel. The reason why I need to use Native SQL statement instead of standard XML structure is that I need to execute a dynamic SQL query in third party database system lke:-
Select Field1 Field2 from TABLE Where Field3 like "%Name'
I expect the the response in the form of XML file which I can pick up using synchornous interface as mentioned on help.sap.com:-
http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/frameset.htm
The value for %Name can change dynamically according to the transaction and hence cannot be inluded as a KEY element in standard XLM structure,
Hence I need to know:-
1. What message mapping I should use in case if I have to use Native SQL statement.
2.What operation mapping I should use in case if I have to use Native SQL statement.
If guess correclty I may have to use Java mapping to do the above activities. Hence I want to know
3 .How do to go about it to do the Java mapping.
Thanks
Ameet>
Ameet Deshpande wrote:
> Dear All,
>
> Can any one please help us in using Native SQL statement in a JDBC receiver channel. The reason why I need to use Native SQL statement instead of standard XML structure is that I need to execute a dynamic SQL query in third party database system lke:-
>
> "
> Select Field1 Field2 from TABLE Where Field3 like "%Name'
> "
> I expect the the response in the form of XML file which I can pick up using synchornous interface as mentioned on help.sap.com:-
>
> http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/frameset.htm
> http://help.sap.com/saphelp_nw04/helpdata/en/64/ce4e886334ec4ea7c2712e11cc567c/frameset.htm
>
> The value for %Name can change dynamically according to the transaction and hence cannot be inluded as a KEY element in standard XLM structure,
>
> Hence I need to know:-
>
> 1. What message mapping I should use in case if I have to use Native SQL statement.
> 2.What operation mapping I should use in case if I have to use Native SQL statement.
> If guess correclty I may have to use Java mapping to do the above activities. Hence I want to know
> 3 .How do to go about it to do the Java mapping.
>
> Thanks
> Ameet
You can use a stored procedure, and call it from jdbc receiver adapter.
I also solve this issue, with a DBLookup in message mapping. You can refer to my blog, and this usefull 3d:
http://simonlesflex.wordpress.com/2010/12/07/pi-oracle-dblookup/
/people/alessandro.guarneri/blog/2006/03/27/sap-xi-lookup-api-the-killer
/people/siva.maranani/blog/2005/08/23/lookup146s-in-xi-made-simpler -
Error when trying to use this query in report region
Hi ,
I am getting "1 error has occurred
Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the ''generic columns'' checkbox below the region source to proceed without parsing. ORA-00933: SQL command not properly ended"
while trying to use this query in reports region .
Pls help.
Thanks ,
Madhuri
declare
x varchar2(32000);
begin
x := q'!select (first_name||' '|| last_name)a ,
count(distinct(session_id)),manager_name
from cappap_log,
MIS_CDR_HR_EMPLOYEES_MV
where DECODE(instr(upper(userid),'@ORACLE.COM',1),0,upper(userid)||'@ORACLE.COM',upper(userid)) = upper(email_address)!';
if :P1_ALL = 'N' then
x:= x||q'!and initcap(first_name ||' '|| last_name)=:P1_USERNAME!';
else
x:= x||q'!and initcap(first_name ||' '|| last_name)like '%'|| :P1_USERNAME||'%'!';
end if;
if :P1_APP_NAME = '%' then
x:= x||q'! and flow_id like '%'!';
else
x:= x||'flow_id = :P1_APP_NAME';
end if;
x:= x||q'! group by first_name||' '|| last_name , manager_name!';
return x;
end;Hi, I am actually stuck here. Can you please let me know which among these is the higher version.
1) Final Release 3.50
Version 3500.3.016
2) Final Release 3.50
Version (Revision 481)
Because it is working fine in the 1st one whereas its throwing that error pop-up in 2nd one(as soon as we select the Change query global definition option) . -
Converting rows to columns using dynamic query.
I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
declare
lv_sql varchar2(32767) := null ;
begin
lv_sql := 'SELECT Iplineno ';
for lv_rec in (SELECT distinct vendor from bidtabs where letting = '10021200' and call ='021')
loop
lv_sql := lv_sql
|| CHR(10)
|| ', MAX( DECODE( vendor, '
|| chr(39)
|| lv_rec.vendor
|| CHR(39)
|| ', bidprice, NULL ) ) as "'
|| lv_rec.vendor
|| '" ' ;
end loop;
lv_sql := lv_sql
|| CHR(10)
|| 'FROM bidtabs where letting = ''10021200'' and call = ''021'' and lineflag = ''L'' '
|| CHR(10)
|| 'GROUP BY iplineno ;' ;
here is the result
BIDPRICE CALL IPLINENO LETTING VENDOR
9,585 021 0010 10021200 C0104
1,000 021 0020 10021200 C0104
1,000 021 0030 10021200 C0104
17 021 0040 10021200 C0104
5 021 0050 10021200 C0104
11,420 021 0010 10021200 K0054
1,100 021 0020 10021200 K0054
1,100 021 0030 10021200 K0054
5 021 0040 10021200 K0054
3 021 0050 10021200 K0054
8,010 021 0010 10021200 V070
900 021 0020 10021200 V070
1,320 021 0030 10021200 V070
11 021 0040 10021200 V070
3 021 0050 10021200 V070
and here is the desired output
CALL IPLINENO LETTING C0104 K0054 V070
021 0010 10021200 9,585 11,420 8,010
021 0020 10021200 1,000 1,100 900
021 0030 10021200 1,000 1,100 1,320
021 0040 10021200 17 5 11
021 0050 10021200 5 3 3Here is the error message I am getting:
RA-06550: line 22, column 43:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << close current delete fetch lock insert
open rollback savepoint set sql execute commit forall merge
pipe -
Workaround for opening a strongly typed cursor using native dynamic SQL
Hi All,
In reading the PL/SQL documentation for Oracle 9i, I noted that the OPEN-FOR
statement with a dynamic SQL string only allows the use of weakly typed cursors.
I have verified this limitation with my own experimentation as follows:
DECLARE
type rec_type is record(
str varchar2(40),
num number(22)
type cur_type is ref cursor return rec_type;
my_cur cur_type;
que varchar2(100);
tab varchar2(40);
BEGIN
tab := 'dynamic_table_name';
que := 'select key_name, key_value from ' || tab || ' where key_name like ''01%''';
open my_cur for que;
loop
if my_cur%found then
dbms_output.put_line('source_name: ' || my_cur.str || ', page_sn: ' || my_cur.num);
exit;
end if;
end loop;
close my_cur;
END;
Running the above trivial example in an anonymous sql block yields the following
errors as expected:
ORA-06550: line 10, column 8:
PLS-00455: cursor 'MY_CUR' cannot be used in dynamic SQL OPEN statement
ORA-06550: line 10, column 3:
PL/SQL: Statement ignored
ORA-06550: line 13, column 54:
PLS-00487: Invalid reference to variable 'MY_CUR'
ORA-06550: line 13, column 7:
PL/SQL: Statement ignored
Is there a workaround to the situation? Since I do not know the table name at run
time, I must use Native Dynamic SQL. I have a long and complex record type
that I wish to return through JDBC using the REFCURSOR Oracle type in order to
avoid having to register an inordinate number of OUT parameters. Moreover, I
would like to return potentially one or more results in a ResultSet. Using the
standard method of registering native SQL types for the IN and OUT bindings
can only return one result. Hence the reason I would like to return a strong
cursor type. Also, the type of query I am doing is complex, and needs to be
executed in a PL/SQL procedure for performance reasons. Therefore simply
executing a SELECT query dynamically built up on the the JDBC client won't
do the trick.
If anybody has experience with a similar problem and would like to volunteer
information on their workaround, I would really appreciate it.
Best Regards,
J. MetcalfWe can use strongly-typed REF CURSORs in DNS, but the typing derives from a table e.g.
TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
so the problem is your use of "return rec_type" bit.
Forgive my bluntness but I think you have misunderstood strong and weak typing. You actually want to be using weakly-typed cursors. I mean this:
Moreover, I would like to return potentially one or more results in a ResultSet. suggests that the structure of your resultset may vary, which is precisely what a weakly-typed ref cursor allows us to do. Then we can use the JDBC metadata methods to interrogate the structure of the resultset, innit.
so try this:
DECLARE
type cur_type is ref cursor;
my_cur cur_type;
que varchar2(100);
tab varchar2(40);
BEGIN
tab := 'dynamic_table_name';
que := 'select key_name, key_value from ' || tab || ' where key_name like ''01%''';
open my_cur for que;
loop
if my_cur%found then
dbms_output.put_line('source_name: ' || my_cur.str || ', page_sn: ' || my_cur.num);
exit;
end if;
end loop;
close my_cur;
END;
ras malai, APC
Cheers, APC -
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. -
How to create a sub total and grand total using my query.
How can I create a sub total for each section and grand total for using my query like this. your help is appreciated. I am working with 9g
WITH BidItemsInformation AS
( SELECT DISTINCT q.iplineno "Line Number", q.section "Section Number",
i.item "Item Number",
initcap(i.idescr) "Description" ,
i.iunits "Unit",
q.qty "Quantity" ,q.price "Engineers Unit Price",
(q.price * q.qty) "Engineers Estimate"
FROM letprop l,
proposal p,
propitem q,
bidlet b,
bidtabs c,
itemlist i,
vendor v,
bidders d
WHERE(l.letting = b.letting
And b.letting = c.letting
And p.cspecyr = i.ispecyr)
AND q.prpitem = i.item
AND p.contid = l.lcontid
AND q.contid = p.contid
AND c.vendor = l.avendor
AND l.CALL = c.CALL
AND q.lineflag = c.lineflag
AND q.iplineno = c.iplineno
AND l.letting = d.letting
AND c.letting = l.letting
AND c.CALL = d.CALL
AND v.vendor = d.vendor
-- AND AND l.letstat = 'A'
AND c.lineflag = 'L'
AND l.letting ='&letting'
AND l.CALL = '&call'
), BiddersInformation AS
-- This is where you make your changes for vendor name and vendor number Do not touch the above code
-- It is always the same for any call number and letting date
( SELECT IPLINENO "BLine Number",
MAX(CASE WHEN VENDOR='K020' THEN bidprice ELSE NULL END) "K020:: Unit Price",
MAX(CASE WHEN VENDOR='K020' THEN bidprice ELSE NULL END) K,
MAX(CASE WHEN VENDOR='H438' THEN bidprice ELSE NULL END) "H438:: Unit Price",
MAX(CASE WHEN VENDOR='H438' THEN bidprice ELSE NULL END) H,
MAX(CASE WHEN VENDOR='U010' THEN bidprice ELSE NULL END) "U010:: Unit Price",
MAX(CASE WHEN VENDOR='U010' THEN bidprice ELSE NULL END) U,
MAX(CASE WHEN VENDOR='G110' THEN bidprice ELSE NULL END) "G110:: Unit Price",
MAX(CASE WHEN VENDOR='G110' THEN bidprice ELSE NULL END) G,
MAX(CASE WHEN VENDOR='H530' THEN bidprice ELSE NULL END) "H530:: Unit Price",
MAX(CASE WHEN VENDOR='H530' THEN bidprice ELSE NULL END) H1
FROM BIDTABS
WHERE LETTING='&letting'
AND CALL='&call'
AND BIDPRICE <> 0
GROUP BY IPLINENO
SELECT BidItemsInformation."Line Number",
BidItemsInformation."Section Number",
BidItemsInformation."Item Number",
BidItemsInformation."Description",
BidItemsInformation."Unit",
BidItemsInformation."Quantity",
BidItemsInformation."Engineers Unit Price",
BidItemsInformation."Engineers Estimate",
BiddersInformation."K020:: Unit Price",
(BidItemsInformation."Quantity" * K) "KGM CONTRACTORS INC",
BiddersInformation."H438:: Unit Price",
(BidItemsInformation."Quantity" * H) "HOFFMAN CONSTRUCTION COMPAN",
BiddersInformation."U010:: Unit Price",
(BidItemsInformation."Quantity" * U) "ULLAND BROTHERS INC",
BiddersInformation."G110:: Unit Price",
(BidItemsInformation."Quantity" * G) "GLADEN CONSTRUCTION INC",
BiddersInformation."H530:: Unit Price",
(BidItemsInformation."Quantity" * H1) "HOOVER CONSTRUCTION CO"
FROM BidItemsInformation,BiddersInformation
WHERE BidItemsInformation."Line Number" = BiddersInformation."BLine Number";
Line Number Section Number Item Number Description Unit Quantity Engineers Unit Price Engineers Estimate K020:: Unit Price
0010 0001 2011601/00003 Construction Surveying LS 1 143,000 143,000 75,000 75,000 67,080 67,080
0013 0001 2013601/00010 Survey Equipment LS 1 25,000 25,000 25,000 25,000 30,000 30,000
0020 0001 2015601/00030 Blast Monitor/Survey LS 1 50,000 50,000 30,000 30,000 35,000 35,000
0030 0001 2021501/00010 Mobilization LS 1 382,250 382,250 809,000 809,000 704,000 704,000
0040 0001 2021602/00010 Well Survey EACH 60 500 30,000 2,150 129,000 1,600 96,000
0050 0001 2031501/00040 Field Office Type D EACH 1 6,367 6,367 4,000 4,000 25,000 25,000
sub total:
1610 0002 2401501/01143 Structural Concrete (1a43) C Y 46 350 16,100 408 18,768 400 18,400
1620 0002 2401501/01362 Structural Concrete (1c62) C Y 68 200 13,600 204 13,872 200 13,600
1630 0002 2401501/03643 Structural Concrete (3y43) C Y 60 600 36,000 592 35,520 580 34,800
1640 0002 2401512/03633 Bridge Slab Concrete (3y33) S F 1,876 24 45,024 28 51,778 27 50,652
1650 0002 2401521/00030 Structure Excavation Class R C Y 17 125 2,125 1,000 17,000 500 8,500
1660 0002 2401541/00010 Reinforcement Bars LB 2,490 2 3,735 1 3,312 1 3,237
1670 0002 2401541/00011 Reinforcement Bars (Epoxy Coated) LB 12,380 2 18,570 1 17,703 1 17,332
1680 0002 2401601/00010 Structure Excavation LS 1 2,500 2,500 2,000 2,000 5,000 5,000
1690 0002 2402583/00020 Ornamental Metal Railing Type Special L F 284 150 42,600 194 55,096 190 53,960
sub total
1820 0003 2401513/00346 Type Curb Railing Concrete (3y46) L F 135 25 3,375 16 2,093 15 2,025
1830 0003 2401513/07447 Type Mod P-4 (Tl-4) Railing Conc (3y46) L F 302 85 25,670 72 21,593 70 21,140
1840 0003 2401541/00010 Reinforcement Bars LB 14,780 1 18,475 1 13,598 1 13,302
1850 0003 2401541/00011 Reinforcement Bars (Epoxy Coated) LB 76,720 1 103,572 1 85,926 1 84,392
1860 0003 2401601/00010 Structure Excavation LS 1 10,000 10,000 116,000 116,000 115,000 115,000
1870 0003 2402583/00020 Ornamental Metal Railing Type Special L F 132 150 19,800 184 24,288 180 23,760
sub total
totalYou can accomplish that using decode with the grouping function. It returns 1 when that column passed as argument was grouped (or is in some total) and 0 otherwise.
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> with t as
2 (select 'New York' city, 'US' country, 1 num from dual
3 union all select 'Los Angeles' city, 'US' country, 2 num from dual
4 union all select 'London' city, 'GB' country, 2 num from dual
5 union all select 'London' city, 'GB' country, 2 num from dual
6 union all select 'London' city, 'GB' country, 7 num from dual)
7 select decode(grouping(country), 0, country, 'GRAND TOTAL') country,
8 decode(grouping(city), 0, city, decode(grouping(country), 0, 'SUBTOTAL')) city,
9 sum(num) num_total
10 from t
11 group by rollup(country, city)
12 /
COUNTRY CITY NUM_TOTAL
GB London 11
GB SUBTOTAL 11
US New York 1
US Los Angeles 2
US SUBTOTAL 3
GRAND TOTAL 14
6 linhas selecionadas.
SQL>
Maybe you are looking for
-
Officejet Pro 8620 won't print from microsoft or thunderbird
I have installed the printer drivers for my new OfficeJet Pro 8620 and am not able to print from Microsoft Word or Thunderbird. I can print from Google Chrome. I am running Windows 7 and have already reinstalled the printer software several times.
-
Whenever i try to play a tv show, itunes stops working
Every time that I try to play a TV show on itunes, it says that itunes has stopped working and windowns is trying to find a solution. Of course, it never does, so I'm stuck. I've tried reinstalling itunes and restarting my computer and all that jazz,
-
How to install from Tiger DVD on Lombard with CD drive
I've installed Jaguar on a G3 Powerbook Lombard, and downloaded XPostFacto 4. I want to install Tiger, but I only have the DVD version, and there is only a CD drive in the computer. Can I install Tiger from a networked DVD drive, or is there another
-
I used to print photos in my HP psc 2210 printer without any problem including the 8X11 enlarged photos, but now it gets caught at the end of the printing resulting in shortened images. Does it have to do with the thickness of the photo paper? It was
-
How to avoid text cutting on iBooks?
Dear All, In epub 3 when multicolumn text used means text cuts on the top and bottom margin, flows on the next page. Kindly suggest me how to avoid these type of errors in iBooks. Thanks, Muzammil