I need to select distinct id and also need another column
MyClass class1 = new MyClass();
Criteria criteria = new Criteria(MyClass.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("col1"));
projList.add(Projections.property("col2"));
criteria.setProjection(Projections.distinct(projList));
class1 = criteria.list();
What will be the return type of criteria.list()?
If i try to assign it to MyClass.class I get ClassCast Exception.
Please assist. How will I get both my columns?
The result of criteria.list() must be a List<Object[]>, so:
List<Object[]> result = criteria.list();
for (Object[] row : result) {
Object col1 = row[0];
Object col2 = row[1];
}
Related
Retrieve company table
GetEntity.java
String table = "company";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Company.class);
List<Company> list = query.getResultList();
...
Retrieve staff table
GetEntity.java
String table = "staff";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Staff.class);
List<Staff> list = query.getResultList();
...
My questions is how do I control the ? from the following:
em.createNativeQuery(q, ?);
List<?> list = q.getResultList();
Any ideas or suggestion?
Another option is to pass the Class entityClass as an argument to your find method and then you can try and derive table name from entityClass by using reflection and use the entityClass as the type argument to your createNativeQuery method.
Hope this helps!
I have a method like below
public List<String> getSimilarResourceNames(String resourceName){
String searchString = "%"+resourceName+"%";
Session session = getSession();
Criteria criteria = session.createCriteria(Resource.class);
criteria.add(Restrictions.like("name", searchString));
return criteria.list()
}
This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?
Use Projection, you can find examples in Hibernate documentation.
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:
Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
fullnames.add(row[0]);
}
I hope this will help you.
I have a small query something like this:
String sqlStr = "select count(*) from MyTable n where primaryKey.userId = :userId and primaryKey.userType = :userType"
String[] paramNames = {"userId", "userType" };
Object[] paramValues = {userId, userType};
List myObjects = (List) hibernateTemplate.findByNamedQueryAndNamedParam("objectsToDeleteForUser", paramNames, paramValues);
and this works fine. I can make a call with a userid and usertype and get one or more matching records.
What I'd like to do now that is have a list of userid's and usertype's and perform the call but not have to iterate over the list but make one call. So basically when userid(0) and usertype(0), userid(1) and usertype(1) ...................
Is it possible to do this with one call in HQL. Something like the IN clause (X).
Thanks
somwthing like this is possible :
hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
hibernateSession.beginTransaction();
List<Object> userId = new ArrayList<Object>();
List<Object> userType= new ArrayList<Object>();
Query q1 = hibernateSession.createQuery("select count(*) from MyTable n where primaryKey.userId IN (:userId) and primaryKey.userType IN (:userType)");
q1.setParameterList("userId", userId);
q1.setparameterList("userType" , userType);
List myObjects = q1.list();
hibernateSession.close();
this should probably work for you
I would like to implement the following SQL query with Hibernate Criteria:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name
I have tried to implement this with Hibernate Criteria but it didn't work out.
Can anyone give me an example how this can be done with Hibernate Criteria?
Thanks!
Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
You can use the approach #Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
If you have to do group by using hibernate criteria use projections.groupPropery like the following,
#Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
I want to construt a hql query like
select PLAN_ID from "GPIL_DB"."ROUTE_PLAN" where ASSIGNED_TO
in ('prav','sheet') and END_DATE > todays date
I am doing in this way but getting an error in setting parameters
s=('a','b');
Query q = getSession().createQuery("select planId from RoutePlan where assignedTo in REG ");
if(selUsers != null) {
q.setParameter("REG", s);
}
where i am doing wrong? Please help in executing this hwl based query having in clause
You need to assign the parameter list in the query. Also note the brackets around the parameter because it is an 'in' query.
Query q = getSession()
.createQuery("select planId from RoutePlan where assignedTo in (:REG) ");
if(selUsers != null) {
q.setParameterList("REG", s);
}
You can read more about how to use parameters in HQL in the hibernate reference, but this is the relevant example pasted from there:
//named parameter list
List names = new ArrayList();
names.add("Izi");
names.add("Fritz");
Query q = sess.createQuery("from DomesticCat cat where cat.name in (:namesList)");
q.setParameterList("namesList", names);
List cats = q.list();