Optional parameter in query does not work for db2 but works in oracle - spring-boot

Below query works fine for Oracle database, but for Db2 it throws error sqlcode -417.
I have looked up similar problems but did not get any definitive answer:
#Query(value = "select * from tableName f where (aC is null or f.a_c = aC)", nativeQuery = true)
Page<tablename> findByFilters(String aC, Pageable pageable);
On execution the error code is -417

One way to solve this problem would be to rewrite the query as the following:
select * from tableName f where f.a_c = coalesce(aC, f.a_c)
The form of query above is likely to be accepted. In order to find out the exact reason of the error you get, it is necessary to trace the actual SQL statement passed to Db2.
Another option of solving the problem may be to add the CAST operator, which would define the data type of your parameter:
select * from tableName f where (cast(aC as integer) is null or f.a_c = aC)
This is suggested in the description of the error you get

Related

Parametrizing a sub query with jdbc PreparedStatement

I have the following query where the first argument itself is a subquery
The java code is:
String query = select * from (?) where ROWNUM < ?
PreparedStatement statement = conn.preparedStatement(query)
statement.setString(1, "select * from foo_table")
statement.setInt(2, 3)
When I run the java code, I get an exception. What alternatives do I have for making the first subquery statement.setString(1, "select * from foo_table") a parameter?
This is not possible, parameter placeholders can only represent values, not object names (like table names, column names, etc) nor subselects or other query elements.
You will need to dynamically create the query to execute using string concatenation, or other string formatting/templating options.

Passing Date to NamedParameterJdbcTemplate in Select query to oracle

I have a query as below which is returning expected records when run from the SQL Developer
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS')
or UPD_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS'));
I think that we will not need to apply TO_DATE when we are passing java.util.Date object as date parameters but the below code snippet is silently returning me 0 records.
My SQL query in Java class is as below:
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > :lastSuccessfulReplicationTimeStamp1
or UPD_TS > :lastSuccessfulReplicationTimeStamp2);
The code which executes the above query is as below but the below code snippet is silently returning me 0 records:
parameters.put("lastSuccessfulReplicationTimeStamp1", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
parameters.put("lastSuccessfulReplicationTimeStamp2", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);
Please advise.
I guess you already found the answer but if anybody else needs it, here's what I've found:
java.sql.Date doesn't have time, just the date fields. Either use java.sql.Timestamp or java.util.Date. Both seems to be working for me with NamedParameterJdbcTemplate.
A little variation to above solution can be when your input(lastSuccessfulReplicationTimeStamp1/lastSuccessfulReplicationTimeStamp2) is a String instead of Date/TimeStamp (which is what i was looking for and found at this link -> may be it can help someone):
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("lastSuccessfulReplicationTimeStamp1", lastSuccessfulReplicationTimeStamp1, Types.TIMESTAMP);
parameters.addValue("lastSuccessfulReplicationTimeStamp2", lastSuccessfulReplicationTimeStamp2, Types.TIMESTAMP);
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);

ScriptUtils.readScript() with DEFAULT_STATEMENT_SEPARATOR is not working

I am trying to execute a sql script from file using ScriptUtils.readScript method:
sql = ScriptUtils.readScript(fileReader,
ScriptUtils.DEFAULT_COMMENT_PREFIX,
ScriptUtils.DEFAULT_STATEMENT_SEPARATOR);
getJdbcTemplate().update(sql);
But I get the error org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar and from the logs I see that semicolon * in the sql statement is not ignored even I am using ScriptUtils.DEFAULT_STATEMENT_SEPARATOR why it isn't working? What's wrong here?
Edit: I know that I can solve this by using:
getJdbcTemplate().update(sql.replace(";", ""));
but maybe there is another solution?
Edit2: Here is example of sql that I need to execute:
INSERT
INTO MYTABLE
(
ID,
MYNUMBER,
MYVALUE
)
SELECT
ID,
0,
B.MYVALUE
FROM ATABLE A,
BTABLE B
WHERE A.ID = B.ID
AND NOT EXISTS
(SELECT 1 FROM MYTABLE M WHERE M.ID = A.ID
);
I don't think you're using ScriptUtils.readScript the right way. The javadocs themselves state:
Mainly for internal use within the framework.
Looking at the source code, it seems that all this function does is load all the lines from a file into a single string, with some logic around comments. The use of the separator in this method is minor and appears only to be relevant if there is a whitespace at the end of it.
If you want to ignore the separator, you'll need to remove it the way that you suggested (with a replace).

getting Hibernate error when using DBMS_RANDOM.value

I would like to achieve same result as the below query using Hibernate SQL, i.e., I would like to get two random records from the table whose ID is not equal to 300. I am using Hibernate 4.1 and Oracle 11g. I ran the below query on Toad and it gives 2 random records. But, when I try to run the HQL, there is error to do with the usage of "DBMS_RANDOM.value".
SELECT * FROM
( SELECT *
FROM table
where ID != '300'
AND q_ID=125
ORDER BY DBMS_RANDOM.value
)WHERE rownum < 3
;
I tried creating criteria and query, but both give Hibernate errors:
Hibernate Message: Invalid path: 'DBMS_RANDOM.RANDOM' [from com.model.table tab where tab.ID != '33092' ORDER BY DBMS_RANDOM.RANDOM]
and my actual hibernate query is:
Query query = session.createQuery("from table tab where tab.ID != '" +agrmId+"' ORDER BY DBMS_RANDOM.RANDOM").setMaxResults(2);
I also tried ORDER BY rand() and that gives an Oracle error.
Thank you for any help.
I solved the problem by adding a property tag in the hibernate mapping file:
<property name="constVal" formula="DBMS_RANDOM.RANDOM" type="long"/>
and then, in the POJO class, I added a variable with getter and setter methods:
private long constVal;
then, in the DAO class, I added the following query:
Criteria crit1 = session.createCriteria(table.class);
crit1.add(Restrictions.ne("id",300));
crit1.add(Restrictions.eq("quesId",125));
crit1.addOrder(Order.asc("constVal"));
crit1.setMaxResults(2);
and that solved it.

Fetch dates (by month or year) stored in TIMESTAMP using JPA

I am facing a problem and I would like you to help me.
It turns out I have one table in my Oracle 11g database where I store failures of one electronic device. The table definition is following:
CREATE TABLE failure
( failure_id NUMERIC NOT NULL
, fecha TIMESTAMP NOT NULL
, module_id NUMERIC NOT NULL
, code NUMERIC
, PRIMARY KEY(failure_id)
);
Where 'fecha' means 'date'.
I need to fetch failures by YEAR or by MONTH for one specific module but I can't. My ORM maps the TIMESTAMP type to java.sql.Date but I don't know how to compare the month in the JPQL sentence. I have tried to use ORACLE functions with native queries but I front with another issue: to cast the results.
I am using JPA 2.0 with Eclipselink 2.3.2.
My doubts are:
Can I use Oracle functions with this version of Eclipselink library? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR FROM f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
I get this error: Unexpected token [(]
Can I use Eclipselink functions? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT('YEAR', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
Same error.
Do you know a simple way to fetch this data using only one query?
I know I can fetch one module and then check failures with loops but I think it is not the best performing solution.
Thanks.
My sources:
Eclipselink JPA functions link
Eclipselink Query Enhancements link
A native query is written in the SQL dialect of your DB so can use DB specific functionality see the createNativeQuery methods of the EntityManager.
However there is another solution, test the timestamp against a lower and upper value:
WHERE f.fecha >= '2012-9-1' AND f.fecha < '2012-10-1'
The syntax in EclipseLink 2.4 for EXTRACT is,
EXTRACT(YEAR, f.fecha)
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#Functions
I used Eclipselink v 2.4 functions and I am getting values using this:
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE SQL('EXTRACT (YEAR FROM ?)', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2 ");
Extracting year from date stored in database avoids to me one comparison between two dates.
Use
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR from f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
I was facing the same problem. I only checked for the correct syntax of that EXTRACT function for oracle and it worked for me! (Notice the FROM clause into the function syntax.
#NamedQuery(name = "Registros.findByFechacaptura", query = "SELECT s FROM Registros s WHERE EXTRACT(YEAR FROM s.fechacaptura) = EXTRACT(YEAR FROM :fechacaptura)")

Resources