i need the hql query that should return the Map as result, I tried hql new map query but it returns the list of map like follows
Session session = sessionFactory.getCurrentSession();
String HQL_QUERY = "select new map(user.id as id, user.fullName as fullName)
from User user";
List<Map<String,String>> usersList = session.createQuery(HQL_QUERY).list();
if this is the only solution then how do i convert a list of map into a single map without looping, because if the query returns more rows then the looping take more time for convertion. Help me.
I would suggest using Criteria and then a result transformer to create a map. Have a look at this for official documentation. This gives you a clue and you can find more samples on net.
Creating a map is not the job of HQL. It's your job. Simply loop over the rows you get from the query:
String hql = "select user.id, user.fullName from User user";
List<Object[]> rows = session.createQuery(hql).list();
Map<String, String> result = new HashMap<>();
for (Object[] row : rows) {
result.put((String) row[0], (String) row[1]);
}
you can use map like below
Query query = session.createQuery("select new map(id,username) from UserDetails");
List<?> idUsernameList=query.list();
Iterator<?> iterator = idUsernameList.iterator();
Map row=null;
while(iterator.hasNext()){
row=(Map)iterator.next();
System.out.println(row);
}
Related
I am not getting output when I am directly passing a list through IN clause, but getting output when passing the values separately.
Working Code below:
List<String> resultList = null;
List<String> list = new ArrayList();
list.add("123");
list.add("456"):
String query = "select * from company where id in('123','456')");
resultList=getJdbcTemplate().queryForList(query, String.class);
Not working code:
List<String> resultList = null;
List<String> list = new ArrayList();
list.add("123");
list.add("456"):
String query = "select * from company where id in(:list)");
resultList=getJdbcTemplate().queryForList(query, String.class);
I want to fetch the query based on the list passed in the query. Could someone help me here
I have created a pojo class Company.java where I have mentioned db column fields.
After the query part,
List<Company> comp = getJdbcTemplate().queryForList(query, Company.class);
Error I am getting :
Incorrect Column count: expected 1, actual 23
What changes I need to do in above line.
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.
Hi, Is it possible how to get data database tables ,column names and column
values etc ?
I have tried sample snippet code please let me know how to get database column names and values ?
public List<String> getAllTables(){
Map<String, ClassMetadata> classMetaDataMap =
hibernateTemplate.getSessionFactory().getAllClassMetadata();
for(Map.Entry<String, ClassMetadata> metaDataMap : classMetaDataMap.entrySet()) {
ClassMetadata classMetadata = metaDataMap.getValue();
AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata;
String tableName = abstractEntityPersister.getTableName();
}
}
In hibernate for getting column names use the following:
ClassMetadata classMetadata = sessionFactory.getClassMetadata(Person.class);
String[] propertyNames = classMetadata.getPropertyNames();
And for getting column values you can use Hibernate Criteria.
Criteria criteria = session.createCriteria(Person.class);
List list = criteria.list();
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 have a dataobject like
class DocInfo
{
String docId;
String corrId;
String familyId;
}
This maps to a database table.
I'm using a combination of session factory and criteria to execute my query in hibernate which returns the rows that match the query on docId.
Query q = getCurrentSession().createQuery("from DocInfo item where item.docId = :docId");
q.setString("docId", docId);
return q;
Is there a way to directly create a data object out of the results of a query ?
Yes, you can get a list of DocInfo using q.list()
List<DocInfo> docInfoList = q.list();
return docInfoList;
Query.list() will execute the query and return a List of DocInfo results.