HQL convert complicated hql to criteria - java

HQL
Query query = getSession()
.createQuery(
"select com from News as news " +
"join news.comments as com " +
"where news.id = :id " +
"order by com.addDate desc"
);
query.setParameter("id", id);
HQL above works fine. Want to change in the criteria api. I can not make. Please help

I suppose you can try something like this.
Criteria c = createCriteria(News.class);
c.add(Restrictions.idEq(id));
Criteria cComment = c.createCriteria("comments",c);
cComment.addOrder(Order.desc("addDate"));
ProjectionList projections = Projections.projectionList();
projections.add(Projections.property("c.id"),"id");
projections.add(Projections.property("c.addDate"),"addDate");
//Other Properties...
c.setProjection(projections)
c.setResultTransformer(Transformers.aliasToBean(Comment.class))
List<News> list = c.list();
Please mind that the Hibernate Criteria API is being deprecated in favor of the JPA Criteria API

Related

query at postgres HOW in Spring JPA

there is here such a request:
select *
from Organization t
where (t.inn,t.kpp) IN(('000000','00000'),('1111111','111111'));
How make this Query in Spring Data JPA.
I tried like this:
#Query(value =
"SELECT t" +
" FROM Organization t" +
" WHERE (t.inn, t.kpp) IN :innKppList")
List findOrganizationsByInnKpp(#Param("innKppList") Map innKppList);
But it does not work...
If you can split up your map into two lists this will work
#Query("SELECT t FROM Organization t WHERE t.inn IN ?1 AND t.kpp IN ?2")
Set<Organization> findByInnAndKpp(List<String> inn, List<String> kpp);

Hibernate many-to-many retrieve list with condition

Im working with hibernate and java. I have an Group class and a User class. They share a many-to-many relationship as shown in this ERD .
What Im trying to achieve is that I want to retrieve a list of groups with the condition that they contain a User with a certain User_id.
In the GroupDao I have defined a function retrieveForUser in which I tried to retrieve the list using hibernate query language:
public List<Group> retrieveForUser(int userid){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("id", userid);
List<Group> list = query.list();
session.getTransaction().commit();
return list;
}
When I try to loop throught the resulting list using:
for(Group g : groupDao.retrieveForUser(user1.getId())){
System.out.println(g.getName());
}
I get the following errormessage:
java.lang.ClassCastException: java.util.HashMap cannot be cast to nl.hu.jelo.domain.group.Group
Question
How can I achieve it so that I end up with an List<Group> with only groups that contain a User with an certain User_id
You do not need to set result transformer. ALIAS_TO_ENTITY_MAP is for other purpose.
Simply do
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", userid);
is good enough.
Something off topic, are you sure you want to handle transaction manually like that?

Setting ORDER BY and LIMIT clause on JPA Query

I'm very, very new to Hibernate and JPA. I want to be able to apply ORDER BY and LIMIT clauses to a Hibernate(?) query, but am coming up empty. NOTE: I inherited this code.
Here is the current code:
public SomeCoolResponse getSomeCoolResponse(String myId) {
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id";
Query q = getEntityManager().createQuery(queryString);
q.setParameter("id", myId);
List<MyThings> list = q.getResultList();
if(list.size() > 0) {
return list.get(0);
}
return null;
}
Instead of getting an entire list and then just returning the first result (which is the only one we need), I'd like to be able to apply a LIMIT 0,1 clause so that the query will be faster. Also, the query needs to be sorted descending on aThing.created which is a UNIX timestamp integer.
I've tried altering queryString like this:
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id ORDER BY aThing.created LIMIT 0,1";
But Hibernate still returns the entire set.
I've looked at using the JPA CriteriaBuilder API, but it hurt my brain.
I'm a total n00b when it comes to this, and any help is greatly appreciated!
I think you need
q.setMaxResults(1);
See also the accepted answer here.
How do you do a limit query in HQL?
As to the "order by" clause you may include it in the queryString.
The JPQL equivalent to LIMIT start,max is:
setFirstResult and setMaxResults:
q.setFirstResult(start);
q.setMaxResults(limit);

More elegant way to write a hibernate query

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

HIbernate query

I want to execute a query using hibernate where the requirment is like
select * from user where regionname=''
that is select all the users from user where region name is some data
How to write this in hibernate
The below code is giving result appropraitely
Criteria crit= HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName));
Well as you alaready said you can either use the Criteria API or create a HQL query:
// Criteria
List<User> users = HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName)).list();
// HQL
String query = "SELECT FROM User WHERE regionName = :region";
List<User> users = HibernateUtil.getSession().createQuery(query).setString("region", regionName).list();
String hql = "SELECT u FROM User u WHERE regionName=:regionName";
Query q = session.createQuery(hql);
q.setParameter("regionName", regionName);
List result = q.list();

Categories

Resources