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();
Related
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());
I am trying to build a query like this:
List<Integer> ids = ...
String query = DSL.select(TABLE.SOMETHING).from(TABLE).where(TABLE.ID.in(ids)).
getSQL();
But I am not able to get the generated query with the values, just the placeholders.
I tried DSL.inline(ids) but it doesnt' work.
How can I do this?
I am using jOOQ 3.4.2.
Thanks for the help.
UPDATE:
Seems I can do this with:
Configuration configuration = new DefaultConfiguration();
configuration.set(SQLDialect.DERBY);
Settings settings = new Settings()
.withStatementType(StatementType.STATIC_STATEMENT);
configuration.set(settings);
DSLContext create = DSL.using(configuration);
String query = create.select(TABLE.SOMETHING).from(TABLE).where(TABLE.ID.in(ids)).getSQL();
If someone can confirm that is th right way, thanks.
You cannot inline a list with jOOQ's DSL.inline() because if you could, the semantics of such a value would be that of a list/array literal in the database, not of a list of individual values.
Correct way to use DSL.inline():
Here's one correct way to pass a list of inlined values to the Field.in(Field<?>...):
List<Integer> ids = ...
String query = DSL.using(configuration) // Use a Configuration or at least a SQLDialect!
.select(TABLE.SOMETHING)
.from(TABLE)
.where(TABLE.ID.in(ids.stream().map(DSL::inline).collect(toList())))
.getSQL();
Inline all bind values on a per-getSQL() basis:
Use Query.getSQL(ParamType)
List<Integer> ids = ...
String query = DSL.using(configuration)
.select(TABLE.SOMETHING)
.from(TABLE)
.where(TABLE.ID.in(ids))
.getSQL(ParamType.INLINED);
Inline all bind values on a per-Configuration basis:
The solution you've mentioned in your question edit is valid as well, of course:
List<Integer> ids = ...
Configuration configuration = new DefaultConfiguration();
configuration.set(new Settings().withStatementType(StatementType.STATIC_STATEMENT));
String query = DSL.using(configuration)
.select(TABLE.SOMETHING)
.from(TABLE)
.where(TABLE.ID.in(ids))
.getSQL();
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
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")));
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