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 ?
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 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'm new to hibernate and I've this SQL query which works perfectly
SELECT count(*) as posti_disponibili from occupazione t inner join
(select id_posto_park, max(date_time) as MaxDate from occupazione
group by id_posto_park) tm on t.id_posto_park = tm.id_posto_park and
t.date_time = tm.Maxdate and t.isOccupied = 0
which gives me all the last items with isOccupied = 0
I was porting it into Hibernate, I've tried to use
result = ( (Integer) session.createSQLQuery(query).iterate().next() ).intValue()
to return posti_disponibili but i got this exception
java.lang.UnsupportedOperationException: SQL queries do not currently support iteration
How can i solve this? I cannot find the equivalent HQL query
Thank you
I would suggest you to use
Query#uniqueResult()
which will give you single result.
select count(*) .....
will always return you a single result.
Hibernate support it's own iterator-like scroll:
String sqlQuery = "select a, b, c from someTable";
ScrollableResults scroll = getSession().createSQLQuery(sqlQuery).scroll(ScrollMode.FORWARD_ONLY);
while (scroll.next()) {
Object[] row = scroll.get();
//process row columns
}
scroll.close();
I need to create subquery using the Criteria API
the current Criteria query which i have created is
Criteria propCriteria = session.createCriteria(PropertyDetail.class);
propCriteria.createAlias("property","prop");
propCriteria.createAlias("country", "country");
propCriteria.add(Restrictions.eq("prop.propertyId",promotionFormBean.getPropertyId()));
The SQL produced by Hibernate is
select * from PROPERTY_DETAILS this_, COUNTRY_MASTER country2_,
PROPERTY_MASTER prop1_, USER_MASTER user6_, ROLE_MASTER role7_,
USER_MASTER user8_ where this_.country_id=country2_.country_Id and
this_.property_id=prop1_.PROPERTY_ID and
prop1_.archive_user_id=user6_.id(+) and
user6_.role_id=role7_.ROLE_ID(+) and
prop1_.create_user_id=user8_.id(+) and prop1_.PROPERTY_ID=?.
What i need to do is to produce the below SQL using criteria
Required:
select * from PROPERTY_DETAILS this_, COUNTRY_MASTER country2_,
PROPERTY_MASTER prop1_, USER_MASTER user6_, ROLE_MASTER role7_,
USER_MASTER user8_ where (this_.country_id=country2_.country_Id or
country2_.controller_order in (select zone_id from
property_zone_mapping where property_id=?)) and
this_.property_id=prop1_.PROPERTY_ID and
prop1_.archive_user_id=user6_.id(+) and
user6_.role_id=role7_.ROLE_ID(+) and
prop1_.create_user_id=user8_.id(+) and prop1_.PROPERTY_ID=?
The bold part of Required section.Property_zone_mapping is one another table which not associated with PropertyDetail.class.
I want somehow to use this table using subquery .
Thanks in advance.
I find criteria queries so much harder to read than HQL. Have you considered a NamedQuery?
#NamedQueries({
#NamedQuery(
name="PropertyDetail.findByPropertyId",
query="from PropertyDetail join property p join country c where p.propertyId = :propertyId"
)
})
public class PropertyDetail {
...
}
public class PropertyDetailDao {
public List<PropertyDetail> findByPropertyId(long propertyId) {
Query query = getSession().getNamedQuery("PropertyDetail.findByPropertyId");
query.setParameter("propertyId", propertyId);
return query.list();
}
}
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();
}