Set list parameter to native query - java

I would like to set parameter to a native query,
javax.persistence.EntityManager.createNativeQuery
Something like that
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Trying this query result in Exception:
Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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
'_binary'??\0♣sr\0‼java.util.ArrayListx??↔??a?♥\0☺I\0♦sizexp\0\0\0☻w♦\0\0\0t\0
f' at line 1
Error Code: 1064
Call: SELECT * FROM Client a WHERE a.name IN ?
bind => [[firstValue, secondValue]]
Query: ReadAllQuery(referenceClass=TABLE_A sql="SELECT * FROM TABLE_A a WHERE a.name IN ?")
Is it any way to set list parameter for native query, without cast to string and append it to sql query?
P.S. I'm use EclipseLink 2.5.0 and MySQL server 5.6.13
Thanks

I believe you can only set list parameters to JPQL queries, not native queries.
Either use JPQL, or construct the SQL dynamically with the list.

It works if you name the parameter:
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN (:names)");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter("names", paramList);

Not a solution but more of a workaround.
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
String queryParams = null;
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Iterator<String> iter = paramList.iterator();
int i =0;
while(iter.hasNext(){
if(i != paramList.size()){
queryParams = queryParams+ iter.next() + ",";
}else{
queryParams = queryParams+ iter.next();
}
i++;
}
query.setParameter(1, queryParams );

You can add multiple values like this example:
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class);
List<String> empNumbers = Arrays.asList("A123", "A124");
List<Employee> employees = query.setParameter(1, empNumbers).getResultList();
Source: PRAGT E., 2020. JPA Query Parameters Usage. Retrieved from: https://www.baeldung.com/jpa-query-parameters

Related

Java native query - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I get following error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Card.findPrefix'"
for:
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c
.number/10000)) FROM Card c")
})
public List<Integer> findPrefix(){
Query q = em.createNativeQuery("Card.findPrefix");
try{
return q.getResultList();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
I can not understand where is my mistake, because when I type this query directly to Mysql it works perfectly.
Use should use createNamedQuery, instead of createNativeQuery.
From EntityManager JavaDoc
createNativeQuery(String sqlString)
Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
createNamedQuery(String name)
Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).
So in your code you are executing query name 'Find....' as SQL query.
The right one:
Query q = em.createNamedQuery("Card.findPrefix");
Final code is:
public List<Integer> findPrefix(){
Query q = em.createNamedQuery("Card.findPrefix");
List<Integer> res = new ArrayList<Integer>();
for(Object row : (List<Object>) q.getResultList()){
res.add(((BigInteger)row).intValue());
}
return res;
}
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c.number/10000)) FROM Card c")
})

How to write criteria eqivalent of sql having count [duplicate]

I need to create a query and I need COUNT(*) and HAVING COUNT(*) = x.
I'm using a work around that uses the CustomProjection class, that I downloaded somewhere.
This is the SQL that I try to achieve:
select count(*) as y0_, this_.ensayo_id as y1_ from Repeticiones this_
inner join Lineas linea1_ on this_.linea_id=linea1_.id
where this_.pesoKGHA>0.0 and this_.nroRepeticion=1 and linea1_.id in (18,24)
group by this_.ensayo_id
having count(*) = 2
This is the code, where I use the Projection Hibernate class:
critRepeticion.setProjection(Projections.projectionList()
.add( Projections.groupProperty("ensayo") )
.add( CustomProjections.groupByHaving("ensayo_id",Hibernate.LONG,"COUNT(ensayo_id) = "+String.valueOf(lineas.size()))
.add( Projections.rowCount() )
);
The error is:
!STACK 0
java.lang.NullPointerException
at org.hibernate.criterion.ProjectionList.toSqlString(ProjectionList.java:50)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getSelect(CriteriaQueryTranslator.java:310)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:71)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:67)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1550)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at ar.com.cse.cseagro.controller.RepeticionController.buscarEnsayo(RepeticionController.java:101)
If I comment the line with CustomProjections class, the query work, but I don't get the HAVING COUNT(*) filter in the SQL ...
Basically the query try to retrieve, in a master - detail schema, all the master records where a list of details are simultaneously present, like if you want tho know "which invoices have both products, A and B".
That why if I got 3 items in the IN clause, I need to use HAVING COUNT = 3 clause.
Any idea or suggestion?
Best regards,
I figured out the problem. I replace CusotmProjections class, with:
.add( Projections.sqlGroupProjection("ensayo_id", groupBy , alias, types));
where groupBy, alias and types are:
String groupBy = "ensayo_id" + " having " + "count(*) = " + String.valueOf(lineas.size());
String[] alias = new String[1];
Alias[0] = "ensayo_id";
Type[] types = new Type[1];
types[0] = Hibernate.INTEGER;
and the magic is on groupby String. –
If someone needs to do it in grails it would be like:
projections {
groupProperty("id")
sqlGroupProjection(...)
rowCount()
}
Where sqlGroupProjection is available since 2.2.0
/**
* Adds a sql projection to the criteria
*
* #param sql SQL projecting
* #param groupBy group by clause
* #param columnAliases List of column aliases for the projected values
* #param types List of types for the projected values
*/
protected void sqlGroupProjection(String sql, String groupBy, List<String> columnAliases, List<Type> types) {
projectionList.add(Projections.sqlGroupProjection(sql, groupBy, columnAliases.toArray(new String[columnAliases.size()]), types.toArray(new Type[types.size()])));
}
http://grepcode.com/file/repo1.maven.org/maven2/org.grails/grails-hibernate/2.2.0/grails/orm/HibernateCriteriaBuilder.java/#267
Here is my sample, it works fine, maybe useful :
My sql query :
select COLUMN1, sum(COLUMN2) from MY_TABLE group by
COLUMN1 having sum(COLUMN2) > 1000;
And Criteria would be :
Criteria criteria = getCurrentSession().createCriteria(MyTable.Class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("column1"), "column1");
projectionList.add(Projections.sqlGroupProjection("sum(column2) sumColumn2 ", "COLUMN1 having sum(COLUMN2) > 1000" , new String[]{"sumColumn2"}, new org.hibernate.type.Type[]{StandardBasicTypes.STRING}));
criteria.setProjection(projectionList);
criteria.List();
criteria.add(Restrictions.sqlRestriction("1=1 having count(*) = 2"));

jpa native query control entity(part 3)

Retrieve company table
GetEntity.java
String table = "company";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Company.class);
List<Company> list = query.getResultList();
...
Retrieve staff table
GetEntity.java
String table = "staff";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Staff.class);
List<Staff> list = query.getResultList();
...
My questions is how do I control the ? from the following:
em.createNativeQuery(q, ?);
List<?> list = q.getResultList();
Any ideas or suggestion?
Another option is to pass the Class entityClass as an argument to your find method and then you can try and derive table name from entityClass by using reflection and use the entityClass as the type argument to your createNativeQuery method.
Hope this helps!

How to use :value for list values in hibernate?

I know that I can write so:
Query query = session.createSQLQuery(
"select s.stock_code from stock s where s.stock_code = :stockCode")
.setParameter("stockCode", "7277");
List result = query.list();
How I must do if I use list values
select count(*) from skill where skill.id in (1,2,4)
I want replace hardcode values.
Maybe:
Query query = session.createSQLQuery("select count(*) from skill where skill.id in :ids")
.setParameter("ids", Arrays.asList(1,2,4));
Query interface have setParameterList(List<any>) function to set the value in IN Clause in HQL. But in HQL IN Clause have a limit to set the element. If the limit is exceed, memory overflow exception occur.
Have you tried something like this?
Query query = session.createSQLQuery(
"select s.stock_code from stock s where s.stock_code in (:stockCodes)")
.setParameter("stockCodes", "1,2,4");
Does it work for you?

hql query formation

I want to construt a hql query like
select PLAN_ID from "GPIL_DB"."ROUTE_PLAN" where ASSIGNED_TO
in ('prav','sheet') and END_DATE > todays date
I am doing in this way but getting an error in setting parameters
s=('a','b');
Query q = getSession().createQuery("select planId from RoutePlan where assignedTo in REG ");
if(selUsers != null) {
q.setParameter("REG", s);
}
where i am doing wrong? Please help in executing this hwl based query having in clause
You need to assign the parameter list in the query. Also note the brackets around the parameter because it is an 'in' query.
Query q = getSession()
.createQuery("select planId from RoutePlan where assignedTo in (:REG) ");
if(selUsers != null) {
q.setParameterList("REG", s);
}
You can read more about how to use parameters in HQL in the hibernate reference, but this is the relevant example pasted from there:
//named parameter list
List names = new ArrayList();
names.add("Izi");
names.add("Fritz");
Query q = sess.createQuery("from DomesticCat cat where cat.name in (:namesList)");
q.setParameterList("namesList", names);
List cats = q.list();

Categories

Resources