How to use named paramater in SELECT query statement in NamedParameterJdbcTemplate - java

Here is the query-
sql = "SELECT EMP_NAME, EMP_NUMBER, EMP_JOINING_DATE, :joiningDate as NAMED_PARAM_DATE from EMP_TABLE where EMP_JOINING_DATE>:joiningDate"
code:
NamedParameterJdbcTemplate jdbcTemplate;
.....
MapSqlParameterSource sqlParams = new MapSqlParameterSource();
sqlParams.addValue("joiningDate", System.getenv("JOIN_DATE"), Types.DATE);
results = this.jdbcTemplate.query(sql, sqlParams, new BeanPropertyRowMapper<Employee.class>(Employee.class))
This gives me below error
nested exception is com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2
SQL Error: SQLCODE=-418, SQLSTATE=42610, SQLERRMC=unresolved untyped
expression, DRIVER=4.25.1301
Is it possible to do that? I can do it alternate way but just wanted to check from Query perspective as we can select any hard-coded value in SQL query using any DB client.
Note: Updated the query for more clarity, also this code works fine when I take out joiningDate from SELECT statement.

Related

My Spring JPA queries do not work with H2

This query below does not work and it generates me an exception
#Query(value = "SELECT * FROM account WHERE account_no = ?1",
nativeQuery = true)
Account findByAccountNo(String accountNo);
"message": "could not prepare statement; SQL [SELECT * FROM account WHERE account_no = ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement",
When I used the MySQL database, the query worked fine. But now that I am using the H2 database, it suddenly does not work. Why? How do I fix this?
It would be better to use JPA.
If you still wanna use nativeQuery, use like this:
#Query(value = "SELECT * FROM account WHERE account_no = :account_no",
nativeQuery = true)
Account findByAccountNo(#Param("account_no") String accountNo);
I'm guessing here, but the parameter syntax "?1" probably is not valid for H2.
There's no need to use a native query here, and if you use Jpa syntax instead, it should work.
Also, you shouldn't need to specify a query here at all - Spring Jpa should generate the query for you.

How to execute a custom sql query in apache spark against Big Query

I have a scenario where I need to execute custom query. The sql query basically deletes the table and creates the same table and insert some data.
sql is something like this
DROP TABLE DEMO.CUSTOMER;
CREATE TABLE DEMO.CUSTOMER AS (
SELECT DISTINCT
CUSTOMERID,
CUSTOMERNAME
FROM DEMO.COMPANY);
INSERT INTO DEMO.CUSTOMER(SELECT CUSTOMERID,CUSTOMERNAME FROM DEMO.COMPANY WHERE AV = 1;
How do I pass the above query in the below code?
HashMap<String, String> options = new HashMap<>();
options.put("credentials", serviceAccountKey);
options.put("project", "customerProject");
options.put("parentProject", "customerProject");
options.put("table", sql);
spark.read().format("bigquery").options(options).load();
In traditional jdbc the sql can be passed along with table parameter. But how do I do that with BQ?

Major performance degradation with named parameters and preventing sql injection using hibernate with native sql

I'm using hibernate 3.6.4.Final and sql server 2008 r2 and got a query on a table with more than 20 million records. Criteria api does unfortunatly generate sub-optiomal queries when paging (select top 100010 from ... for result 100000 - 100010 ) when using firstResult / maxResult so I've reverted to native sql.
This queries run blazingly fast in sql studio but using named or positional parameters in hibernate those queries crawl painfully slow. Googling along I couldn't find any solution so I'm currently concatenating parameters which allows sql injections, but this is of course no option for production!
Now I'm wondering if there's something I've overlooked or at least some hibernate api or library I'm not aware of which I could use to sanitize parameters before rolling my own and probably failing to catch some edge case...
Unfortunately, Criteria API is the best way to avoid sql injection, but it is so slow, the best way is to use normal Hibernate Queries with dynamic parameters, i mean For ex:
String stringQuery ="select * from User as u where id = :id";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
OR u can make your query more dynamic by creating a new Class MyQueryBuilder
public class myQueryBuilder(){
public Query buildQuery(int id){
String stringQuery ="select * from User as u where u.id = :id";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
return query;
}
public Query buildQuery(int id,String name){
String stringQuery ="select * from User as u where u.id = :id and u.name = :name";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
query.setParameter("name",name);
return query;
}
...
//Later you can call the query builder methods as you want depending on your params
}
and remember that it is always safe using setParameter() Method

How to use JPA Prepared statment for Insert query in java

I would like to know how to use prepared statement for insert query. Generally for select query I am using in following way.
Query query = JPA.em()
.createNativeQuery("select item_status from item_details where box_id=:boxnumber");
query.setParameter("boxnumber", boxNumber);
But when I am using insert query I am unable to use in the above way.
Query query = JPA.em()
.createNativeQuery("insert into item_details values(':item_status')");
query.setParameter("item_status", itemstat);
I am getting error like
java.lang.IllegalArgumentException:
org.hibernate.QueryParameterException: could not locate named parameter [item_status]
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:368) ~[hibernate-entitymanager-3.6.9.Final.jar:3.6.9.Final]
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72) ~[hibernate-entitymanager-3.6.9.Final.jar:3.6.9.Final]
please any one help me to sort out this issue. Thanks in advance
I could't tested but could you try this;
Query query = JPA.em().createNativeQuery("insert into item_details(item_status) values(?)") .setParameter(1, itemstat).executeUpdate();

jOOQ - error with alias and quotes

I have this query:
Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
String.class, LICENZE.CREATION_DATE).as("anno_mese");
List<Record3<Integer, String, String>> records =
create.select(DSL.count().as("num_licenze"), LICENZE.EDIZIONE, yearMonth).
from(LICENZE).
groupBy(LICENZE.EDIZIONE, yearMonth).
orderBy(yearMonth).
fetch();
this query generates:
select
count(*) "num_licenze",
"PUBLIC"."LICENZE"."EDIZIONE",
FORMATDATETIME("PUBLIC"."LICENZE"."CREATION_DATE", 'yyyy-MM') "anno_mese"
from "PUBLIC"."LICENZE"
group by
"PUBLIC"."LICENZE"."EDIZIONE",
"anno_mese"
order by "anno_mese" asc
executing it i get: Column "anno_mese" not found; SQL statement
Testing the generated query and removing the quotes from anno_mese in every parts of the query make the query works instead.
Is my query wrong or am I using jooq in the wrong way?
The alias in this query is not so important, I can run the query without using it too but just to understand how it works.
I am using h2 as database.
Thanks for the help
I suspect this is a bug in H2, which I've reported here, because the query looks fine to me. Here are some workarounds that you can do from the jOOQ side:
Don't reference the "anno_mese" column by name
While SQL is a bit repetitive otherwise, you won't notice the difference with jOOQ. I simply moved the as("anno_mese") method call into the SELECT clause. You don't really need it in the GROUP BY and ORDER BY clauses.
Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
String.class, LICENZE.CREATION_DATE);
List<Record3<Integer, String, String>> records =
create.select(DSL.count().as("num_licenze"),
LICENZE.EDIZIONE,
yearMonth.as("anno_mese")).
from(LICENZE).
groupBy(LICENZE.EDIZIONE, yearMonth).
orderBy(yearMonth).
fetch();
Disable quoting in jOOQ generated queries
You can use jOOQ's Settings to prevent schema / table / column names from being quoted. Example:
DSLContext create = DSL.using(connection, SQLDialect.H2,
new Settings().withRenderNameStyle(RenderNameStyle.AS_IS);
Use upper case column names
This will probably work: DSL.field(...).as("ANNO_MESE")

Categories