Below is mysql query which is working fine and giving me expected results on mysql console.
select * from omni_main as t where t.date_time BETWEEN STR_TO_DATE(CONCAT('2011', '08', '01'),'%Y%m%d') AND LAST_DAY(STR_TO_DATE(CONCAT('2012', '08','01'), '%Y%m%d')) group by year(date_time),month(date_time)
I need its JPA equivalent query. Below is what I am trying but its returning nothing.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN STR_TO_DATE(CONCAT('"+fromYear+"', '"+fromMonth+"','01'), '%Y%m%d') AND "
+"LAST_DAY(STR_TO_DATE(CONCAT('"+toYear+"', '"+toMonth+"','01'), '%Y%m%d'))";
Query query = manager.createQuery(queryStr);
System.out.println("Result Size: "+query.getResultList().size());
Here fromYear, fromMonth, toYear, toMonth are method parameters using in creating queryStr.
Please suggest where I may wrong!
Any other way to achieve goal is also welcome!
As you are using JPA Query, it would be better to not use database-specified sql function, such as STR_TO_DATE.
You can have a try by this way.(A Hibernate way, JPA should be similiar):
First, you can parse a java.util.Date object from "fromYear" and "fromMonth" like below:
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date startDate = df.parse(fromYear + "" + fromMonth + "01");
Date endDate = df.parse(.....);
Then, set them into the JPA query.
String queryStr = "select * from OmniMainEntity o where o.dateTime BETWEEN :startDate AND :endDate)"; // The query now changed to database independent
Query query = manager.createQuery(queryStr);
query.setDate("startDate", startDate);
query.setDate("endDate", endDate);
At last, doing the search:
System.out.println("Result Size: "+query.getResultList().size());
Your query doesn't have a verb in it. You probably want SELECT in there:
SELECT o FROM OmniMainEntity o WHERE...
Also, you should be using parameterized and typed queries, and it's usual to use short names (o instead of omniMainEnt) to make your queries readable.
Related
I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
My code is
String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.
I'm expecting list size is 0 because there are no records w.r.t userId passed.
What changes do I need to do?
Lets say the value of userId was "abc12"
Given your code, the value of the string called hql would become:
"FROM com.pck.Person where userId = abc12"
If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.
As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:
String hql = "FROM com.pck.Person where userId = :id"
query.setParameter("id", userId);
Looks like you are missing single quotes around userid.
Try with "FROM com.pck.Person where userId = '" + userId + "'";
or
Use named parameters with query.setParameter("userid", userId);
Posting the full stacktrace would help if this doesn't solve.
If I have a query which runs on SQL which is :
String contactWhere = " UNION SELECT FoldContact.FoldRSN,NULL PeopleRSNCode,'A' FileIndicator from People,Contact"
But how we pass NULL PeopleRSNCrypt and 'A' FIleIndicator in jooq. if we have
SelectQuery<Record> selectQuery = create.selectQuery();
selectQuery.addSelect(Contact.FOLD_CONTACT.FOLD_RSN);
Use Factory.value("A").as("FIleIndicator") and Factory.inline(null).as("PeopleRSNCrypt")
Hibernate doesn't support union ,so i would like to run sql separately. but finally how to combine those values ?
String query ="select
dp.PRODUCTFAMILY,dp.PRODUCTFAMILYDESCR
from TABEL1 dd, TABEL2 DP
where dd.id = 00002
and dd.PRODUCTFAMILY is null
union
select
dp.DIVNUMBER,dp.DIVDESCR
from TABEL1 dd, TABEL2 DP
where dd.id = 00002
and dd.PRODUCT is not null and dd.PRODUCTFAMILY is not null";
public List<PRODUCT> findmethod() {
return findAllByQuery(query);
}
Please advise how to execute two sql seperately and finally how to combine those values ?
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
If this is true add alias to your query:
select
dp.PRODUCTFAMILY as PRODUCTFAMILY,dp.PRODUCTFAMILYDESCR as PRODUCTFAMILYDESCR
from TABEL1 dd, TABEL2 DP
where dd.id = 00002
and dd.PRODUCTFAMILY is null
union
select
dp.DIVNUMBER as PRODUCTFAMILY,dp.DIVDESCR as PRODUCTFAMILYDESCR
from TABEL1 dd, TABEL2 DP
where dd.id = 00002
and dd.PRODUCT is not null and dd.PRODUCTFAMILY is not null
You can use SQLQuery and a AliasToBeanResultTransformer in this manner:
session.createSQLQuery(above sql with union).addScalar("PRODUCTFAMILY",StringType.INSTANCE).addScalar("PRODUCTFAMILYDESCR",StringType.INSTANCE).setResultTransformer(new AliasToBeanResultTransformer(PRODUCT.class))
PRODUCT must have an emtpy constructor and field accessors.
Else, if this union is intended to extract different fields with different types you have to run two queries separately the addAll() second result to first!
would like to share, which in my case, I found a situation that skirted this situation. The only rule here is to have the same type, in this case String, corresponding to return the list, could add as many tables you want:
public List<String> findByCPForCNPJ(String query){
TypedQuery<String> ccpf = manager.createQuery("select cpf from PessoaFisica where cpf like :pCpf", String.class);
ccpf.setParameter("pCpf", "%" + query + "%");
List<String> lista1 = ccpf.getResultList();
TypedQuery<String> ccnpj = manager.createQuery("select cnpj from PessoaJuridica where cnpj like :pCnpj", String.class);
ccnpj.setParameter("pCnpj", "%" + query + "%");
lista1.addAll(ccnpj.getResultList());
return lista1;
}
I used a method in JAVA for this solution.
I hope I have contributed a bit, good luck to all...
The records in the db look like this:
10//12/2013
10/13/2013
10/16/2013
10/20/2013
I want to search 2013 in the above records. Do i have to split first above values?
from CustomerRelations where DATE like'" + input + "'
Can I use like here?
Or how else can I do this?
Query q = session.createQuery("from CustomerPayment where DATE like '" + code + "'");
The Above code does not work.
Since you've saved the dates as VARCHAR do a wildcard String match
Query q = session.createQuery("from CustomerPayment where DATE like '%" + code + "'");
LIKE clause lets you use two wilcards:
_ = matches just one single character
% = matches any number of characters
Ideally, you should have created your table with a TIMESTAMP column. That would allow you to compare dates accurately and build queries like "fetch all customer payments in the last three months" etc.
you can use
datepart(year,datefield)
where datefield is your field from which you want to retrieve the year
Query q = session.createQuery("SELECT date FROM CustomerPayment WHERE datepart(year,"+Convert.ToDateTime(datefield)+")="+ input+";
Try changing your query to
Query q = session.createQuery("SELECT date FROM CustomerPayment WHERE date LIKE '%"+input+"'"
since your date field is a string, you must do the lookup via a string compare
How can we implement the Hibernate sqlprojection in my query?
Here is my query
SELECT sum(total_amount) as total,created_at from order where created_at < DATE_SUB(curdate(), INTERVAL 7 DAY) and doctor_id = 193 GROUP BY created_at
I have implement DATE_SUB function using sqlRestriction like this:
String sqlWhere = "created_at > DATE_SUB(curdate(), INTERVAL "+activityGraph+" DAY) AND doctor_id = "+id +" GROUP BY created_at";
Criteria criteria = Hibernatesession.createCriteria(Order.class);
criteria.add(Restrictions.sqlRestriction(sqlWhere));
But I don't know how I get the sum of a field using Hibernate query.
I found out that setProjection in Hibernate is used to get the sum as we desired but I don't know how to use it. Also here I want to use sqlRestriction to write WHERE condition for date_sub function.
So I will use setProjection and sqlRestriction in a single query.
You're making you life difficult. Why don't you simply compute the date limit in Java before executing the query?
Date today = DateUtils.truncate(new Date(), Calendar.DATE);
Date limit = DateUtils.addDays(today, -7);
And since the query is completely static, why using the Criteria API. HQL is much easier:
String hql = "SELECT sum(o.totalAmount) as total, o.createdAt from Order o"
+ " where o.createdAt < :limit"
+ " and o.doctor.id = 193"
+ " group by o.createdAt";
criteria.setProjection((Projections.sum("/* name of the mapping variable for total_amount*/")));
public int getSum() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Product.class);
criteria.setProjection(Projections.sum("productCount"));
List list = criteria.list();
session.getTransaction().commit();
return (int) list.get(0);
}
//hibernate mpping
<property name="productCount" type="int" column="PRODUCT_COUNT"/>