Hibernate Native SQLQuery extract values - java

How can I extract multiple values from native SQLQuery?
SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);
When I use query.list() or query.uniqueResult, it returns always list of Object\Object, which cannot be cast to anything even if I add scalars.
No problems on extraction single value:
session.createSQLQuery("SELECT param1 from table_name where ..);
Long result = (Long)query.uniqueResult();
But how can I extract 2 or more values ?

According to SQLQuery.list() API:
Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[]
Sample code:
SQLQuery query = session.createSQLQuery("SELECT param1, param2 from table_name where ..);
List<Object[]> list = (List<Object[]>)query.list();//Object[] objs = (Object[])query.uniqueResult()
for (Iterator<Object[]> iterator = list.iterator(); iterator.hasNext();) {
Object[] e = iterator.next();
String param1 = (String)e[0];//case object type to another by youself...
}
If your program add scalar to SQLQuery, Hibernate could return match object type as you expected.

Related

SQL Query Hibernate with clause where

how should be this query in hibernate
public Double getValuPrice(int param1, int param2){
Query query = session.createQuery("FROM TableClass WHERE e.product= :param1 and e.type = :param2");
query.setParameter("param1 ",param1);
query.setParameter("param2",param2);
result = query.uniqueResult();
List lista = query.list();
return lista;
}
and i want show the value returned in a Servlet
List list = classDao.getValuPrice(origem, destino);
out.println("<h1>" + list.eq(0) + "</h1>");
In your query you are doing from TableClass and then WHERE e.product = :param1. I would have thought that would give you an error along the lines of Unable to resolve path [e.product], unexpected token [e]. Also you have a rogue space in one of your parameters, which will give you a could not locate named parameter [param1 ] error.
You don't, however, need the select * as suggested by Lenin's answer (see the Hibernate manual (v4.3 §11.4.1 "Executing Queries"))
So correcting these:
remove the space in "param1 "
specify a type for result (and do a cast) - unless result is a field you haven't shown in your sample code
and, of course, remove e. before your properties in the query (or add e as an alias for TableClass)
You are returning a List but the method specifies a Double - I'm not sure what you want to do here so you'll need to work that out yourself.
The code now looks like
public Double getValuPrice(int param1, int param2){
Query query = session.createQuery("FROM TableClass WHERE product= :param1 and type = :param2");
query.setParameter("param1",param1);
query.setParameter("param2",param2);
// assuming result is a field with type TableClass
result = (TableClass)query.uniqueResult();
List lista = query.list();
return lista; // <-- fix the return statement
}
If you want to return a specific field on TableClass, which is a Double (e.g. double price;) then do:
Query q = session.createQuery("select price from TableClass WHERE product= :param1 and type = :param2"
...
Double result = ((Number) q.uniqueResult()).doubleValue();
Seems like you are missing Select clause and table alias.
It should be like
Query query = session.createQuery("Select * FROM TableClass e WHERE e.product= :param1 and e.type = :param2");

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 get map as result of HQL

i need the hql query that should return the Map as result, I tried hql new map query but it returns the list of map like follows
Session session = sessionFactory.getCurrentSession();
String HQL_QUERY = "select new map(user.id as id, user.fullName as fullName)
from User user";
List<Map<String,String>> usersList = session.createQuery(HQL_QUERY).list();
if this is the only solution then how do i convert a list of map into a single map without looping, because if the query returns more rows then the looping take more time for convertion. Help me.
I would suggest using Criteria and then a result transformer to create a map. Have a look at this for official documentation. This gives you a clue and you can find more samples on net.
Creating a map is not the job of HQL. It's your job. Simply loop over the rows you get from the query:
String hql = "select user.id, user.fullName from User user";
List<Object[]> rows = session.createQuery(hql).list();
Map<String, String> result = new HashMap<>();
for (Object[] row : rows) {
result.put((String) row[0], (String) row[1]);
}
you can use map like below
Query query = session.createQuery("select new map(id,username) from UserDetails");
List<?> idUsernameList=query.list();
Iterator<?> iterator = idUsernameList.iterator();
Map row=null;
while(iterator.hasNext()){
row=(Map)iterator.next();
System.out.println(row);
}

Set list parameter to native query

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

How do I convert result of a Query directly to my data object in Hibernate?

I have a dataobject like
class DocInfo
{
String docId;
String corrId;
String familyId;
}
This maps to a database table.
I'm using a combination of session factory and criteria to execute my query in hibernate which returns the rows that match the query on docId.
Query q = getCurrentSession().createQuery("from DocInfo item where item.docId = :docId");
q.setString("docId", docId);
return q;
Is there a way to directly create a data object out of the results of a query ?
Yes, you can get a list of DocInfo using q.list()
List<DocInfo> docInfoList = q.list();
return docInfoList;
Query.list() will execute the query and return a List of DocInfo results.

Categories

Resources