I know that I can write so:
Query query = session.createSQLQuery(
"select s.stock_code from stock s where s.stock_code = :stockCode")
.setParameter("stockCode", "7277");
List result = query.list();
How I must do if I use list values
select count(*) from skill where skill.id in (1,2,4)
I want replace hardcode values.
Maybe:
Query query = session.createSQLQuery("select count(*) from skill where skill.id in :ids")
.setParameter("ids", Arrays.asList(1,2,4));
Query interface have setParameterList(List<any>) function to set the value in IN Clause in HQL. But in HQL IN Clause have a limit to set the element. If the limit is exceed, memory overflow exception occur.
Have you tried something like this?
Query query = session.createSQLQuery(
"select s.stock_code from stock s where s.stock_code in (:stockCodes)")
.setParameter("stockCodes", "1,2,4");
Does it work for you?
Related
I'm relatively new to Spring JPA CriteriaQuery. Im trying to convert my old native query in my program to criteria query and haven't been successful on join query for multiple table with conditions. I need help converting native SQL query into Criteria Query for these query below :
select * from student s inner join (
select distinct on (student_id) * from class where status = 'Active' order by
student_id,date_register desc) c on s.id = c.user_id
inner join teacher t on t.subject_id = c.subject_id
where t.status = 'Active' and s.status='Active' order by s.name desc
Update :
Below code is as far as I can go cause I dont really know much. Am i in the right direction? I'm opting for Expression because i dont know how to use Join.
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> sRoot= query.from(Student.class);
query.select(sRoot);
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Class> cRoot= subquery.from(CLass.class);
Expression<Integer> max = cb.max(cRoot.get("dateRegister"));
subquery.select(max);
subquery.groupBy(cRoot.get("student"));
query.where(
cb.and(
cb.in(cRoot.get("dateRegister")).value(subquery)
)
);
Thanks in advance!
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)
I have a situation where I need to convert a query like :-
select hostname, avg(cpu_utilization_percentage) from cpu_utilization where timestamp In (select distinct(timestamp) from report.cpu_utilization order by timestamp desc limit 6) group by hostname
Now, this data I want to fetch using hibernate so I have used Subqueries:-
// For inner Query
DetachedCriteria subquery = DetachedCriteria.forClass(CpuUtilizationDTO.class);
subquery.setProjection(Projections.distinct(Projections.property("timeStamp"))).addOrder(Order.desc("timeStamp"));
subquery.getExecutableCriteria(session).setMaxResults(6);
// For Outer Query
Criteria query = session.createCriteria(CpuUtilizationDTO.class);
ProjectionList list = Projections.projectionList();
list.add(Projections.groupProperty("hostName"));
list.add(Projections.avg("cpuUtilizationpercentage"));
query.setProjection(list);
List<Object[]> obj= (List<Object[]>)hibernateTemplate.findByCriteria(query);ction(list);
//Now to add subquery into main query I am using
query.add(Subqueries.propertyIn("timeStamp", subquery));
But everytime I am getting the average of entire data. Can anyone please help that where did I miss?
I run following code intend to update the least record in the table on Hibernate 3.6.7 final (JPA 2.0?) :
Query query = em.createQuery("UPDATE MyTable a SET a.isEnable=1 WHERE a.isEnable=0 ORDER BY a.id DESC").setMaxResults(1);
query.executeUpdate();
but hibernate ignores ORDER BY when generating sql.
Is ORDER BY for SELECT use only in JPQL? How to execute UPDATE query with ORDER BY in JPA?
thanks for any help.
To update the record with the last ID in a table you do the following:
TypedQuery<MyEntity> query = em.createQuery("SELECT a FROM MyEntity a WHERE a.isEnable=0 ORDER BY a.id DESC", MyEntity.class);
query.setMaxResults(1);
List<MyEntity> resultList = query.getResultList();
if (resultList.size()>0) {
resultList.get(0).setEnabled(true);
//eventually you can to em.flush();
}
I am trying to get just the count of the rows returned rather than all the results from the table.
I saw that this can be done like this:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
But when trying to store this query in an integer format(it says cannot convert from Query to Integer)
I am using a dynamic query where the values will be mentioned below the query like this
theQuery = "select count(*) from THM as thm " +
"join thm.TMC as tmc " +
"join tmc.TIMCC as timcc " +
"where thm.Qid = :Qid and thm.Cv = :Cv and timcc.Did = :Did and timcc.Cv= :Cv";
Query query = session.createQuery(theQuery);
query.setInteger("Qid", Integer.parseInt(Qid));
query.setInteger("Did", Did);
query.setInteger("Cv",cV);
Now, how can i get a count of all the rows returned by using Hibernate query in a variable without using list.size but directly from the query?
Have you tried the query.uniqueResult(); ? As your Select count(*) will give you only one number, you should be able to retrieve it with this like int count = (Integer)query.uniqueResult();
To count based on a Criteria you can do this:
Criteria criteria = currentSession().createCriteria(type);
criteria.setProjection(Projections.rowCount());
criteria.uniqueResult();
I'm using the Criteria right now so I know for sure that it works. I saw the uniqueResult() solution on a website here: http://www.jroller.com/RickHigh/entry/hibernate_pagination_jsf_datagrid_prototype1
you can do this
long count = (long)session.createQuery("SELECT COUNT(e) FROM Employees e").getSingleResult();
Try it.
Long count = ((Long) session.createQuery("select count(*) from Book").uniqueResult());
Integer totalBooks = count.intValue();
Work for me
int list=(int)
sessionFactory.getCurrentSession().createSQLQuery("select count(*) as count from
Book").addScalar("count",IntegerType.INSTANCE).uniqueResult();