how to use 'group by' on hql? - java

I have a native query I need to change to HQL.
The original query is:
SELECT COUNT(DISTINCT `table`.`id`) FROM `database`.`table` WHERE
(`table`.`date`" " BETWEEN '" + year + "-01-01 00:00:00' AND '" + year
+ "-12-31 23:59:59') AND `table`.`box` NOT LIKE '' GROUP BY MONTH(`table`.`date`)";
I tried something like:
StringBuilder hql = new StringBuilder();
hql.append(" select count(distinct table.id)");
hql.append(" from Table table");
hql.append(" where table.date between '?-01-01 00:00:00' and '?-12-31 23:59:59'");
hql.append(" and table.box not like ''");
hql.append("group by month (table.date)");
query.setParameter(1, Integer.toString(year));
query.setParameter(2, Integer.toString(year));
Where year is a int passed to the method as argument.
The generated query is:
Hibernate: select count(distinct table0_.id) as col_0_0_ from table table0_ where (table0_.date between '2013-01-01 00:00:00' and '2013-12-31 23:59:59') and (table0_.box not like '') group by month(table0_.date)
My problem is: using the native query, I get one value and using the hql I get another for month 2 (February). For month 1 (January) results are the same.
What am I missing here?
Thanks in advance,
gtludwig

They seem to be the same query without the schema qualification to me. Aren't you running them in different instance? Like, one in 'database' and the other pointing to anoher base with similar data loaded?

Related

Java trying to extract data according to timestamps in sql, returning inaccurate results

I am trying to extract data from mysql tables according to timestamps like 'Top votes of the Month' and 'Top votes of the week'
This is mysql statement for collecting top vote of the week (week 4)
"SELECT * FROM studentid.questions WHERE vote IN (SELECT MAX(vote) FROM studentid.questions WHERE timestamp BETWEEN '"+currentYear+"-"+currentMth+"-19 00:00:00' AND '"+currentYear+"-"+currentMth+"-24 23:59:59');
This is mysql statement for collecting top vote of the month (may)
"SELECT * FROM studentid.questions WHERE vote IN (SELECT MAX(vote) FROM studentid.questions WHERE timestamp BETWEEN '"+currentYear+"-05-01 00:00:00' AND '"+currentYear+"-05-31 23:59:59')"
Somehow, the sql statement returns results OUTSIDE of the date ranges, for example, if in the month of may, there is a data with votes equal to another data in the month of february, it will display both of them, when it should only display from may...
sql results
The root cause of the problem you describe is probably due to the time zone difference between the server and your app, or from the way you are using parameters. If it's the latter you should change the code to use JDBC parameters as shown below:
First you compute the "from" and "to" timestamps in Java, and then you apply them:
Timestamp fromTS = ...
Timestamp toTS = ...
PreparedStatement ps = conn.createStatement(
"SELECT * " +
"FROM studentid.questions " +
"WHERE vote IN ( " +
" SELECT MAX(vote) FROM studentid.questions " +
" WHERE timestamp BETWEEN ? AND ?)"
);
ps.setTimestamp(1, fromTS);
ps.setTimestamp(2, toTS);
ResultSet rs = ps.executeQuery();
...

How to retrieve data and count of data at same time in hql?

I want to retrieve count and list of data in one query only which I want to write on JPA repository. I wrote it using a constructor and executed using entity manager, but it didn't work. It gave me a QuerySyntaxException. Here is my query:
String hql = "select new core.abc(select count(*) from abc as m where m.Id in :Ids and m.Type = :Type,"
+ "select max(m.modificationTime) from abc as m where m.Id in :Ids and m.Type = :Type )";
How can I write such kind of query in JPA repository?
I just figure out your use case senario is that you want to get all records from table as well as total-count of records and max value of a specific column , you named that column as modificationTime. So onething will be happen in this case, if you want to intract with table with single query, Than you will get useless data for both column named as max and count.
Try This for JPA,
#Query(value="SELECT cb from abc cd where cd.Id in (?1) and cd.Type=?2 , (SELECT MAX(m.modificationTime) as maxModificationTime , COUNT(*) as count FROM abc m where m.Id in (?3) and m.Type=?4) as m",nativeQuery=true)

SQLSyntaxErrorException - ORA-02287: sequence number not allowed here

In my java code, i am trying to perform insert operation but for some reasons i am getting SQLSyntaxErrorException . I am not getting the reason behind it though i tried. Below is my code.
Query nativeQuery = em.createNativeQuery(
"insert into TABLE_DIMENSION (DIMESNION_ID, DIMENSION_CODE, TABLE_CODE, TABLE_IND, CREATE_TIME, "
+ "CREATE_PLACE, CHG_DT, CHG_WARDANT) "
+ " (select TABLE_DIMENSION_SEQ.nextval, d.name,:dimensionCode, 0, :time, :place, :date, :wardant from table_master d where d.name in (:table_dimension_ids)) ");
nativeQuery.setParameter("date", new Date());
nativeQuery.setParameter("table_dimension_ids", tableDimensionList);
nativeQuery.setParameter("dimensionCode", dimensionCode);
nativeQuery.setParameter("wardant", wardant);
number = nativeQuery.executeUpdate();
Please guide.
You told your query that you will use 6 parameters but you set just 4 parameters, you are missing to put :place and :time in the parameters like the others, so you have to use :
nativeQuery.setParameter("place", place);
nativeQuery.setParameter("time", time);
before you execute your query, else you have to remove it from your query
You should skip ():
insert into TABLE_DIMENSION
(DIMESNION_ID, DIMENSION_CODE, TABLE_CODE, TABLE_IND
, CREATE_TIME, CREATE_PLACE, CHG_DT, CHG_WARDANT)
select TABLE_DIMENSION_SEQ.nextval, d.name,:dimensionCode, 0
, :time, :place, :date, :wardant
from table_master d
where d.name in (:table_dimension_ids)

HQL not working "in" with multiple values

I have hibernate which goes something like this.
String queryString = "from MFunction as mFunction where mFunction.functionKey in "
+ "((select mRole.enterprise from MRole as mRole where mRole.roleKey=:role), "
+ "(select mRole2.project from MRole as mRole2 where mRole2.roleKey=:role ), "
+ "(select mRole3.technology from MRole as mRole3 where mRole3.roleKey=:role ))";
But the hibernate query takes in only the first value.
Hibernate: select mfunction0_.FunctionKey as Function1_73_, mfunction0_.`Add` as Add2_73_, mfunction0_.`Audit` as Audit3_73_, mfunction0_.ClientKey as ClientKey73_, mfunction0_.CreatedBy as CreatedBy73_, mfunction0_.CreatedTs as CreatedTs73_, mfunction0_.`Delete` as Delete7_73_, mfunction0_.`Edit` as Edit8_73_, mfunction0_.`Financial` as Financial9_73_, mfunction0_.FunctionName as Functio10_73_, mfunction0_.`General` as General11_73_, mfunction0_.Level as Level73_, mfunction0_.LevelKey as LevelKey73_, mfunction0_.LogicalDeleteTms as Logical14_73_, mfunction0_.UpdatedBy as UpdatedBy73_, mfunction0_.UpdatedTs as UpdatedTs73_, mfunction0_.`View` as View17_73_ from appanalytixdb.M_Function mfunction0_ where mfunction0_.FunctionKey in (select mrole1_.Enterprise from appanalytixdb.M_Role mrole1_ where mrole1_.RoleKey=?)
Hibernate version: 4.1.8.Final
Your problem is that you created a list of lists, and you should create a single list of functionkeys.
I see only 2 options:
Change one 'in' to 3 statements connected with or.
String queryString = "from MFunction as mFunction where mFunction.functionKey in (select mRole.enterprise from MRole as mRole where mRole.roleKey=:role) or mFunction.functionKey in (select mRole2.project from MRole as mRole2 where mRole2.roleKey=:role ) or mFunction.functionKey in (select mRole3.technology from MRole as mRole3 where mRole3.roleKey=:role )";
Best solution would be to preselect all projects,technologies,enterprise and union them together (to avoid duplicates). But hibernate does not yet support union, according to this post Hibernate Union alternatives.
If you have not so many entries in your tables, I would create a view, and used my query on it. Views can be quite cheap and easy to use in this scenarios.

Delete query in mysql

I want to delete rows from multiple tables. I know the select query, but I need an exact delete query for all the columns that are defined below:
SELECT j.application_id,
j.first_name,
j.last_name,
c.description,
l.description,
p.description, " +
"j.email,
j.date_applied,
j.application_status,
j.dob, j.current_city, j.phone_mobile, j.phone_residence " +
"FROM jobapp.job_applications j,
jobapp.countries c,
jobapp.countries l ,
jobapp.job_locations p " +
"WHERE j.preferred_location = p.id
AND j.current_country = l.id
AND j.nationality = c.id "; //+
//"and application_status like ? and first_name like ? and last_name like ? and email like ?";
The query works fine using MySQL, but I need an delete query for the exact columns where the rows are get deleted...
delete statements are structured like:
DELETE FROM table WHERE condition.
you should replace condition with the primary key from you query above (if it is present) and reference each table one at a time.

Categories

Resources