Hibernate Subqueries - java

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?

Related

Convert SQL Query to Criteria Query in Spring Boot

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!

Best approach to delete 2000 records using JPQL in spring-jpa

If in the database table, the records limit exceeds 10000 (10K) , then i need to delete old 2000 (2K) based on timestamp by using JPA name query.
Below are my named queries,
#NamedQuery(name = FIND_COMMN_LOG_ID_BY_DEVICE_ID,
query = "select entity.id from table1 entity where entity.deviceId =:deviceId ORDER BY recordedTime ASC"),
#NamedQuery(name = DELETE_LOG_BY_DEVICE_ID_BASED_ON_TIMESTAMP,
query = "delete from table1 entity where entity.id in (:IdList)")})
There are used this way:
List<Integer> list = entityManager.createNamedQuery(Constants.FIND_COMMN_LOG_ID_BY_DEVICE_ID)
.setParameter("deviceId", deviceId)
.setMaxResults(2000)
.getResultList();
int count = entityManager.createNamedQuery(Constants.DELETE_LOG_BY_DEVICE_ID_BASED_ON_TIMESTAMP)
.setParameter("IdList", list)
.executeUpdate();
Above queries are working but i am getting performance issues and it is taking a lot of time to delete 2000 records and server is crashing also.
Can anyone has better simple and fast approach to delete 2000 records?
Thanks in Advance!!
Try something like that :
#NamedQuery(name = FIND_COMMN_LOG_ID_BY_DEVICE_ID, query = "select entity from table1 entity where entity.deviceId =:deviceId ORDER BY recordedTime ASC"),
List entities = entityManager.createNamedQuery(Constants.FIND_COMMN_LOG_ID_BY_DEVICE_ID).setParameter("deviceId", id).execute();
entityRepository.deleteInBatch(entities);

Hibernate Criteria create a count query without asking it beside The query

I create a query using criteria (java) on PostgreSQL DB ,
This is a snippet from my code:
protected Criteria createEntityCriteria() {
return createEntityCriteria(getSession());
}
protected Criteria createEntityCriteria(Session session) {
return session.createCriteria(getEntityClass(), "main").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
Criteria crit = createEntityCriteria();
crit.setFirstResult((pagingInfo.getPageNumber() - 1) * pagingInfo.getPageSize());
crit.setMaxResults(pagingInfo.getPageSize());
now when i view the log from hibernate(criteria query) i see 2 queries
the first one:
the first query which i have NOT asked at all is:
/* criteria query */ select
count(*) as y0_
from some_Table this
left outer join moreTable
on ......
the second one is which i did asked for:
Hibernate:
/* criteria query */ select col1 y0_,
col2 y1_,
......
from .....
left join ....
on ....
order by
y41_ desc limit ? offset ?
the problem is that the count query fail due to a query time out .
and second one works perfect .
is there a way to prevent from hibernate to "made-up" this count query ?

Select rows with max date hibernate

I need to write a criteria query for selecting rows with max date:
Criteria criteria;
//getting criteria
criteria.add(Restrictions.sqlRestriction("{alias}.date = (__QUERY_FOR_MAX_DATE__)"));
Is it possible to avoid writting sqlRestriction derictly and do it merely with Criteria query?
I mean applying some projections, or something similar... Without writing the sql-restriction explcicitly.
DetachedCriteria innerCriteria = DetachedCriteria.forClass(ClassName.class, "inner")
.setProjection(Projections.projectionList().add(Projections.max("inner.dateColumnName")));
Criteria crit = session.createCriteria(ClassName.class, "outer");
crit.add(Subqueries.propertyEq("outer.dateColumnName", innerCriteria));

How to update only one row in table but with greatest id number by JPQL

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();
}

Categories

Resources