distinct query with jpa,jasper report - java

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

Related

Apache Ignite cache "IN" clause not working

What I want to do is
final String query = "select userName from users where userId in
(?) and isActive = 1";
SqlFieldsQuery sql = new SqlFieldsQuery(query);
List<Long> userIds = new ArrayList<Long>();
userIds.add(140l);
userIds.add(245l);
sql.setArgs(userIds.toArray());
List<List<?>> rsList = usersCache.query(sql).getAll();
. It is not giving the desired result. It is returning only one result
instead of two.
Please suggest
It's impossible to pass an array as an argument for in. You can rewrite your query to use a join instead. It will look as follows:
select u.userName from users u
join table (userId bigint=?) t on u.userId=t.userId
where u.isActive=1
Another thing you should take into account is that SqlFieldsQuery.setArgs(...) takes a vararg as an argument. So, to prevent your array from being unfolded, you should add a cast to Object:
sql.setArgs((Object)userIds.toArray());

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

Getting the occurrence of values using JpaRepository Queries

I have a class named Submission and another SubmissionDAO for the repository. The submission class has a number of fields such as id, author, title,...
What I want to do is search through the database and get a list of (count, author) pairs for each author value in the database.
I made a query
#Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Submission> findByAuthorOccurance();
Obviously, this doesn't work because it can't put the count value in the Submission object.
My question is how would I go about getting this pair of values back to my controller?
I've tried searching but nothing comes up.
In case anyone comes here in the future for whatever reason, I figured my problem out.
When you specify a range of data points to get from the query (ie author and count), it groups the values into object arrays (Object[]) and puts those in a normal List.
So my code ended up being like this:
#Query(value = "select author, count(*) from submissions GROUP BY author order by count(author) desc", nativeQuery = true)
List<Object[]> findByAuthorOccurance();
For the query and
List<Object[]> map =submissionRepository.findByAuthorOccurance();
for(Object[] objs : map){
System.out.println((String)objs[0]+" : "+(BigInteger)objs[1]);
}
To get the data.

How to pass list in hql query where list is a value of a map

I have a leaveList containing 4 leave names.This leaveList is passed as map value.I want to get leave details from CompanyLeave Table by passing leaveList in hql query.Let be considered,my Company Leave Table contains 6 leave details.leaveList has 3 leave names.I want to get details of these 3 leaves from CompanyLeave Table.
Code for Hql query here leaveNameList is a list as well as map
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("companyCode", params.get("companyCode"));
query.setParameter("leaveNames", params.get("leaveNameList"));
List<CompanyLeaveType> validLeaveDetails = query.list();
return validLeaveDetails;
}
N.B: I have got java.util.ArrayList cannot be cast to java.lang.String error.How can I pass list in hql query?
Use query.setParameterList(), Check the documentation here.
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("leaveNames", params.get("leaveNameList"));
Here you are trying to add a list object to the Hql query.
Here in this case the generated query by hibernate looks like this(actually its not happened and is just to make you to understand whats going on here)
1) Select *from companyLeveType_Table where companyCode=someX and leaveName in(ListObject)
But here the leaveName is of type java.lang.String and hence hibernte frameworks expects the values should be the string only. see the sample code (Hibernte expects this)
2) Select *from companyLeveType_Table where companyCode=someX and leaveName in("A","B","C");
from first query its obvious that hibernate framework tries to convert the java.util.ArrayList to java.lang.String and hence exception throws.
Solution 1)
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Query query = sessionfactory.getCurrentSession().createQuery("from CompanyLeaveType WHERE companyCode = :companyCode and leaveName IN (:leaveNames)");
query.setParameter("companyCode", params.get("companyCode"));
query.setParameterList("leaveNames", params.get("leaveNameList")); // changes here only remaining is same
List<CompanyLeaveType> validLeaveDetails = query.list();
return validLeaveDetails;
}
Solution 2:
Use Criteria api.
public List<CompanyLeaveType> getByValidLeave(Map<String, Object> params) {
Criteria criteria=session.createCriteria(CompanyLeaveType.class);
criteria.addCriteria(Restrictions.eq("companyCode",params.get("companyCode")))
.addCriteria(Restrictions.in("leaveName",params.get("leaveNameList")));
List<CompanyLeaveType> validLeaveDetails =criteria.list();
return validLeaveDetails;
}
I hope this helps you

How can I find a list of entities by multiple possible values (Using or in Spring Data)

I have a table of users and I want to get users of certain type (type 2 and type 3 for example).
If I wanted to find by Type 2 , the repository interface would have a method
List<User> user = userDao.findByType(2);
I could get the users for type 2 and 3 by running the above method twice.
But I was wondering if it is possible to get the result set in one queury.. Something along the lines of
List<Long> types = new List<Long>();
types.add(2);
types.add(3);
List<User> usersOfType2And3 = userDao.findByType(types);
You can also make use of Criteria api for same,
Criteria crit = session.createCriteria(User.class);
Criterion crit1 = Restrictions.eq("type", new Integer(2));
Criterion crit2 = Restrictions.eq("type", new Integer(3));
crit.add(Restrictions.or(crit1, crit2));
List<User> usersList = crit.list();

Categories

Resources