Restrict selected fields using Hibernate Criteria projection - java

I have an HQL query, but it has many where conditions. So I decided to use Hibernate Criteria.
Here is my query:
select distinct u.employee.id,u.employee.name,u.employee.address.phone from user u.
I tried it using the Criteria Project.property. But it gives an error. Is it possible to write Hibernate Criteria for this query?

Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("employee.id"), "id")
.add(Projections.property("employee.name"), "Name"));
List<User> list = cr.list();
Few more examples.
Criteria cr = session.createCriteria(Employee.class);
// To get total row count.
cr.setProjection(Projections.rowCount());
// To get average of a property.
cr.setProjection(Projections.avg("salary"));
// To get distinct count of a property.
cr.setProjection(Projections.countDistinct("firstName"));
// To get maximum of a property.
cr.setProjection(Projections.max("salary"));
// To get minimum of a property.
cr.setProjection(Projections.min("salary"));
// To get sum of a property.
cr.setProjection(Projections.sum("salary"));

List<User> users = (List<User>) dbSession.createCriteria(User.class)
.add(Restrictions.eq("nameOfFieldInUserClass", value))
.list();
"nameOfFieldInUserClass" is name of restriction field in User, not name of column in DB.
and for distinct you can use
setProjection(Projections.distinct(Projections.property("nameOfField")));

Related

How to use OR queries in greenDAO?

I have a query like:
Select * from table where user = 'user1' or city = 'delhi';
I know how to do it for single user but I am not getting how can I use or in following query.
dao.queryBuilder()
.where(UserDao.Properties.UserId.eq(userId1))
.list();
For Version 3.2.+, here is an example to use a combination of Where() and WhereOr() conditions. The below is a hypothetical query to select all items:
That have the tags 'paint', 'emulsion'
That belong to a specific Category
Excluding a particular Sub Category
The Where() method takes exactly one query condition and the WhereOr() can take multiple query conditions (as many as the number of properties in the Dao Class), separated by comma
String catgId = "AB12545";
String excludeSubCatgId = "SAB09990";
DaoSession daoSession = ((App) getApplication()).getDaoSession();
List<Item> = daoSession.getItemDao().queryBuilder()
.where(ItemDao.Properties.CategoryId.eq(catgId))
.where(ItemDao.Properties.SubCategory.notEq(excludeSubCatgId))
.whereOr(ItemDao.Properties.ItemTagCloud.like("%paint%"),
ItemDao.Properties.ItemTagCloud.like("%emulsion%"))
.orderDesc(ItemDao.Properties.ItemPrice)
.list();
In order to use or conditions in greenDAO, you have to use or method in QueryBuilder object.
Example:
QueryBuilder<User> qb = dao.queryBuilder();
qb.where(UserDao.Properties.UserId.eq(userId1), qb.or(UserDao.Properties.City.eq("delhi")));
List<User> users = qb.list();
For more details, see the "Queries" section in greenDAO documentation.
Try this:
QueryBuilder<User> qb = dao.queryBuilder();
qb.whereOr(UserDao.Properties.UserId.eq(userId1),
UserDao.Properties.City.eq("delhi"));
List<User> users = qb.list();

Pagination with ordered data with hibernate

Using hql in hibernate we can do pagination on a table data using below, but below will return first 5 data records in the table.
String SQL_QUERY = "FROM Order order";
Query query = session.createQuery(SQL_QUERY);
query.setFirstResult(1);
query.setMaxResults(5);
But how can i do the pagination on a ordered data on a table for example an ordered data set by a order_id ?
Not sure what you're asking, but just add order by clause in your query, and calculate first result based on page. Something like this
String HQL_QUERY = "FROM Order o order by o.id";
Query query = session.createQuery(HQL_QUERY);
// page size
query.setMaxResults(5);
// page 1
query.setFirstResult(1);
// page 2
query.setFirstResult(6);
...

JPA Typed query set parameter

I have a named parameter in JPA typed query. I am setting a list of value in condition.
I am setting a list of integer, but when JPA converts typed query to corresponding sql query it is adding a to_number function and index of the table is not used.
List<Integer> studentIds=ArrayList<Integer>
//Student id is number in database and indexed.
query = "SELECT T.* FROM STUDENT WHERE STUDENT_ID IN (:studentIds)"
TypedQuery<Object[]> typedQuery = entityManager().createQuery( query, Object[].class);
typedQuery.setParameter("studentIds", studentIds);
The issue is when JPA generates the query it is adding to_number function to convert the list
SELECT * from student t4 where student_id in (?,?,?);
filter("T4"."student_id"=TO_NUMBER(:9) OR "T4"."student_id"=TO_NUMBER(:10) OR
"T4"."student_id"=TO_NUMBER(:11) OR "T4"."PRODUCT_SET_ID"=student_id(:12)
Any thoughts how to make sure JPA does not add a to_number function, so index will be used.
I had to use an array when I was passing values into a '.in' predicate. Try this:
List<Integer> studentIds=ArrayList<Integer>
Integer[] ids = new Integer[studentIds.size()];
ids = studentIds.toArray(ids);
//Student id is number in database and indexed.
query = "SELECT T.* FROM STUDENT WHERE STUDENT_ID IN (:studentIds)"
TypedQuery<Object[]> typedQuery = entityManager().createQuery( query, Object[].class);
typedQuery.setParameter("studentIds", ids);

How to add Distinct in Hibernate Criteria

In my database I have a Test table, with columns: testName, testType
there are 2 different tests with the same type I.e "SUN", so I want only one of them for which I use Distinct in my hibernate / criteria as below, but it still giving me both the types with the same name as "sun".
Criteria crit = session.createCriteria(Test.class);
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
crit.setResultTransformer(trans);
List rsList = trans.transformList(crit.list());
Any idea what could be the reason, or any other way of filtering duplicates.
Use Projections.distinct.
Criteria crit = session.createCriteria(Test.class).setProjection(
Projections.distinct(Projections.projectionList()
.add(Projections.property("type"), "type") )
.setResultTransformer(Transformers.aliasToBean(YourBean.class));
List lst = crit.list();
where YourBean.class has a property "type". The returned list will be List<YourBean>.
Try to use :
cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
It work perfectly for me
I finally have found out to get values of other columns:
Criteria criteria = session.createCriteria(Test.class);
ProjectionList projectionList = Projections.projectionList();
ProjectionList projectionList2 = Projections.projectionList();
projectionList2.add(Projections.distinct(projectionList.add(Projections.property("distinctColumn"), "distinctColumn")));
projectionList2.add(Projections.property("col1"), "col1");
projectionList2.add(Projections.property("col2"), "col2");
criteria.setProjection(projectionList2);
criteria.setResultTransformer(Transformers.aliasToBean(Test.class));
List list = criteria.list();
Try to use :
Criteria criteria =
session.createCriteria(Test.class).setProjection(
Projections.distinct(Projections.property("testType")));
List<Test> rsList = criteria.list();
Had the same problem and ended up solving using the Group By projection and then adding in all the columns I needed. For example
Criteria query = session.createCriteria(Class.class)
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("Col1"), "Col1")
.add(Projections.groupProperty("Col2"), "Col2"))
.setResultTransformer(Transformers.aliasToBean(Class.class));
List list = query.list();
Try
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
Criteria crit = session.createCriteria(Test.class);
List list = crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
Projections provide the result of the marked properties only. but, it creates problem for the child entities. See my post for the real problem I faced it.
Hibernate: Parent and Child relationship data structure
Try using:
criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
It uses default hashcodes to find matches in results.
Thanks.

distinct query with jpa,jasper report

I am using ireport-4.5.0,spring3.0.5RELEASE,jpa2. I have an entity class named as User and having the attributes as follow
userId,
userName,
password.I
Designed the jrxml by giving the fields as these three attributes names.If i give the jpa Query as From USer then it is working fine and giving the result. But i want the distinct values of userName(userName column allows duplicate values also)so i have given the jpaQuery as
SELECT userId,DISTINCT(userName),password FROM User
Then i am not getting the result.What is the problem with the query.
Hi here i am giving the code i am using
public User getUsers() throws Exception{
Query uQuery = entityManager.createQuery("SELECT u.userId,u.userName,u.password FROM User u GROUP BY u.userId,u.userName,u.password");
List <User>listOfUsers = uQuery.getResultList();
if (listOfUsers == null) {
throw new ResourceNotFound();
}
for (Iterator iterator = listOfUsers.iterator(); iterator.hasNext();) {
User userList = (User)iterator.next();
}
return userList;
Here i am getting the ClassCastException:java.lang.String cannot be cast to User.It is showing this exception in the for loop statement.I am new to JPA.Can you please explain how to iterate that list of objects.
You cannot put DISTINCT on a single column in JPQL or SQL.
You most likely need to use a group by,
SELECT u.userId,u.userName,u.password FROM User u group by u.userId, u.userName, u.password

Categories

Resources