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");
Related
I want to implement update query in JPA. I tried this:
public void updateTransactionStatus(String uniqueId, String type, String status) throws Exception {
String hql = "update " + PaymentTransactions.class.getName()
+ " e SET e.status = :status WHERE e.unique_id = :unique_id AND e.type = :type";
TypedQuery<PaymentTransactions> query = entityManager.createQuery(hql, PaymentTransactions.class).setParameter("status", status).setParameter("unique_id", uniqueId).setParameter("type", type);
query.executeUpdate();
}
But I get Update/delete queries cannot be typed. What is the proper wya to implement this?> I tried to replace TypedQuery with Query but I get The type Query is not generic; it cannot be parameterized with arguments <PaymentTransactions>
In general if you do not need to you should avoid using batch updates with JPA unless they are triggered from within a REQUIRES_NEW marked transaction (and thats the only operation).
It seems that you need to perform an update on one unique entry so I would suggest a query followed by a modification, thats it:
// retrieve
PaymentTransactions paymentTransaction =
entityManager.createQuery("select t from " + PaymentTransactions.class.getName()
+ " where e.unique_id = :unique_id AND e.type = :type "
, PaymentTransactions.class);
.setParameter("unique_id", uniqueId).setParameter("type", type)
.getSingleResult();
// modify
paymentTransaction.setStatus(status);
Here is the place for a TypedQuery.
As long as your method is within a transactional context, thats all you need to do to update the entry.
when i run my query in database visualizer its working perfectly, but i think there are some issues in syntax when i convert it in my DAO class method.
I want to get whole data against the name provided
In Visualizer:
SELECT first_name,last_name,nic,phone,email FROM x_hr_user where (first_name = 'Irum');
Now in Dao
public List<XHrUser> findXHrUserByNameInTable()
{
String name ="Irum";
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = (name)");
List<XHrUser> list = query.getResultList();
return list;
}
Instead of showing single row, it displays whole data Table
Thank you
Your current query is not valid JPQL. It appears that you intended to insert the raw name string into your query, which could be done via a native query, but certainly is not desirable. Instead, use a named parameter in your JPQL query and then bind name to it.
String name = "Irum";
Query query = em.createQuery("SELECT x FROM XHrUser WHERE x.firstName = :name")
.setParameter("name", name);
List<XhrUser> list = query.getResultList();
You have to write query as below. where : is used for variable
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = :name");
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.
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!
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();