My sql query
SELECT count(1),trunc(D_O_I) FROM TableName
WHERE P_D IN (3) AND
D_O_I BETWEEN to_date('01/01/2014','mm/dd/yyyy') and to_date('01/31/2015','mm/dd/yyyy') group by trunc(D_O_I)
And my Hibernate code for query is as below..
session = HibernateSessionFactory.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TableName.class).setProjection(Projections.projectionList()
.add(Projections.groupProperty("dteOfIss"), "dteOfIssResult").add(Projections.rowCount(), "count")).setResultTransformer(Transformers.aliasToBean(GroupedDateDTO.class));
criteria.add(Restrictions.sqlRestriction("(P_D IN ('3'))"));
if (reportsForm.getFromDate() != null && reportsForm.getToDate() != null) {
criteria.add(Restrictions.sqlRestriction("trunc(D_O_I) >= to_date('"+ utils.convertDateToString(reportsForm.getFromDate()) + "', 'MM/dd/yyyy')"));
criteria.add(Restrictions.sqlRestriction("trunc(D_O_I) <= to_date('"+ utils.convertDateToString(reportsForm.getToDate()) + "', 'MM/dd/yyyy')"));
}
listResult = criteria.list();
How to add Trunc to dteofIss in hibernate code? i tried diffrent way's but i am unable to fetch.
Please Help
Related
Can someone help me to have a look at what is wrong with my query?
Java code :
public boolean fValidLogin(String fUsername, String fPassword) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
String query = "SELECT fusername,fpassword FROM flogin WHERE fusername=" + fUsername + " AND fpassword=" + fPassword + "";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) {
it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}
MYSQL Code:
SELECT fusername,fpassword FROM flogin WHERE fusername="SAS" AND fpassword="Sas123"
Try this first:
"SELECT fusername,fpassword FROM flogin WHERE fusername=\"" + fUsername + "\" AND fpassword=\"" +fPassword +"\""
By the way you are tring to use a native query. Maybe you should consider to use "createNativeQuery" instead of "createQuery"
Your query is a victim of an SQL Injection, it can also cause syntax error, instead you have to use setParameter with a JPQL query :
String query = "SELECT f FROM flogin f WHERE f.fusername = ? AND f.fpassword = ?";
Query dBquery = session.createQuery(query);
dBquery.setParameter(0, fUsername);//set username variable
dBquery.setParameter(1, fPassword);//set password variable
To get the nbr of result you can just call Query::list()
int count = dBquery.list().size();
Or just :
return dBquery.list().size() == 1;
The real problem in your query is that the String should be between two quotes (but i don't advice with solution)
fusername='" + fUsername + "'
//--------^_________________^
Note: Your query is not a JPQL Query, it seems a native query, if that you have to use session.createNativeQuery(query);.
I'm using hibernate in my project and I'm trying to convert an existing sql query from DaoImplementation class to hql,
The sql query I have is
JdbcTemplate select = new JdbcTemplate(dataSource);
String sql = "SELECT * FROM (SELECT site_id,rtc,sigplan,cycle_time,health,phase_no,phase_time,active_groups,groupscolour,ip "+
"FROM status_data where rtc>='" + fromDate + "' and rtc<'" + toDate + "' and "+
"site_id=" + SiteId + " order by rtc desc limit "+recordLimit+" )as temp ORDER BY RTC ASC";
I wrote the hql version to get data from HealthLog table as
String hql = " select f from (select h from HealthLog h where rtc>='"+fromDate+"' and rtc <'"+toDate+"' "
+ "and siteId = "+siteId+" order by rtc desc limit "+limit+" ) as f order by rtc asc ";
return super.readListByHql(hql);
But the above hql throws the following exception
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 16 [ select f from (select h from com.traff.hibernate.model.HealthLog as h where rtc>='1974-08-01 14:10:00.0' and rtc <'1974-09-01 23:46:20.6' and siteId = 20 order by rtc desc limit 50000 ) as f order by rtc asc ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:276)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.intern
I also tried the below code snippet but that giving me wrong results
Criteria criteria = createEntityCriteria();
criteria.add(Restrictions.ge("rtc", fromDate));
criteria.add(Restrictions.lt("rtc", toDate));
criteria.add(Restrictions.eq("siteId", siteId));
criteria.setMaxResults(limit);
criteria.addOrder(Order.asc("rtc"));
criteria2 = criteria;
criteria2.addOrder(Order.desc("rtc"));
return criteria2.list();
Which is the correct way to achieve the result?
First of all, as already mentioned in the comments, you cannot do a subquery within the FROM clause in HQL.
See: Hibernate Documentation
Secondly, the limit keyword is not supported by HQL.
Usually you would use query.setFirstResult(0) and query.setMaxResults(recordLimit) methods where query has the type of the Query Interface. But since you are using the limit in a subquery, there is no way.
See: How to set a limit to inner query in Hibernate?
Some options:
Use a native SQLQuery
Since you are only sorting in the outer Query. You could only execute the inner query and sort in Java.
Example for Option 2:
Session session = factory.openSession();
Query query = session
.createQuery("FROM HealthLog "
+ "WHERE rtc >= :rtcL and rtc < :rtcG and siteId = :siteId "
+ "ORDER BY rtc DESC");
query.setParameter("rtcL", fromDate);
query.setParameter("rtcG", toDate);
query.setParameter("siteId", siteId);
query.setFirstResult(0);
query.setMaxResults(recordLimit);
List<HealthLog> res = query.list();
session.close();
Collections.sort(res, new Comparator<HealthLog>() {
public int compare(HealthLog o1, HealthLog o2) {
return o1.getRtc().compareTo(o2.getRtc());
}
});
The query above returns HealthLogs with all attributes. If you want to only retrieve specific attributes, you can add a SELECT new HealthLog(siteId,rtc,sigplan,cycle_time,...) to your Query with a fitting constructor in HealthLog.
Please note that the code snippet might not be ready to use, since i do not know your model and attribute names.
I am facing some issue with the following query.
for (String string : projects) {
String sql = "SELECT eff.id,eff.taskNo,eff.projectId,sum(eff.hours),eff.employeeId FROM EffortCalculator eff where eff.projectId='"
+ string + "' and eff.dayDate >= '2014-12-15' and eff.dayDate <= '2014-12-16' GROUP BY eff.projectId";
System.out.println("sql" + sql);
SQLQuery query = session.createSQLQuery(sql);
System.out.println(query.list());
// query.addEntity(EffortCalculator.class);
list.addAll(query.list());
}
When I execute this query in MySQL DB it works fine. It actually contains two rows. But when I use this query in hibernate it gives empty list.
When I use Hibernate query language, how can I add dinamically the object I want to get from the DB?
What I want to reach is somethin like this:
......
if(....){
queryString = "from '" + Object1+ "'";
}
if(...){
queryString = "from '" + Object2+ "'";
}
....
Session session = this.getSessionFactory().getCurrentSession();
Query query = session.createQuery(queryString);
......
I tried different kind of syntax but I get errors every time.
Via Criteria API you can easily build dynamic query's...
Criteria criteria = session.createCriteria(Sale.class);
if (startDate != null) {
criteria.add(Expression.ge("date",startDate);
}
if (endDate != null) {
criteria.add(Expression.le("date",endDate);
}
List results = criteria.list();
you can use this:
......
if(....){
queryString = "from '" + Object1.getClass().getName()+ "'";
}
if(...){
queryString = "from '" + Object2.getClass().getName()+ "'";
}
....
Session session = this.getSessionFactory().getCurrentSession();
Query query = session.createQuery(queryString);
......
What actually you need is to pass class name. You can use following way to get class name of a given object.
object1.getClass().getSimpleName()
So in your case you can append this in your query
example :
if(....){
queryString = "from '" + Object1.getClass().getSimpleName()+ "'";
}
Can someone help me write a better code. I tried this but its not working :
Query query = session.createQuery("from MyTable order by :sortvariable :sortorder");
query.setParameter("sortvariable", sortvar);
query.setParameter("sortorder", order);
This is not working as well
Query query = session.createQuery("from MyTable table order by table." + sortvar + " " + " :sortorder");
query.setParameter("sortorder", order);
I managet to get it working with this :
Query query = session.createQuery("from MyTable table order by table." + sortvar + " " + order);
I need to do this with query because I'm using setMaxResults() and setFirstResult().
I don't think you can use parameters to identify keywords that way. Is it possible to do what you're trying to do using the criteria API?
boolean sortAscending = ...;
Criteria criteria = session.createCriteria(MyTable.class);
criteria.addOrder(sortAscending? Order.asc(sortVar): Order.desc(sortVar));