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.
Related
Is it possible to retrieve data from a query straight into the EmployeeForm?
Query as stored procedure empdata
SELECT a.name,b.username,b.password FROM Tbemployee left join Tbuser
Code
List<EmployeeForm> form = new ArrayList<EmployeeForm>();
EmpDB service = (EmpDB) RuntimeAccess.getInstance().getServiceBean(
service.begin();
Session session = service.getDataServiceManager().getSession();
SQLQuery query = session.createSQLQuery("EXEC empdata");
List list = query.list();
formList = list;
This gives me an error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.emp.form.EmployeeForm
You need to use a ResultTransformer
The other option is to cast to List<Object[]> which contains rows with columns from the query result, and then iterate and extract data(more work).
The transformer could be something like:
query.setResultTransformer(Transformers.aliasToBean(EmployeeForm.class));
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 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 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);
}
I am trying to select a single column from a related table. I have a table (Item) with many Values. I would like to select Value.valueString.
Basically, the query is supposed to pass in a bunch of values and pull any ValueFields that contain those values. The SQL might look something like this:
select ItemValues.valueString from ItemEntity
join StockItem on ItemEntity.stockItemId = StockItem.id
join ItemValues on ItemEntity.id = ItemValues.itemId
where StockItem.vendor = vendorId
AND (ItemValues.valueString like '%test%' OR ItemValues.valueString like '%test2%'...);
Here is my code:
final CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<String> query = builder.createQuery(String.class);
final Root<ItemEntity> root = query.from(ItemEntity.class);
query.select(root.join("ItemValues").<String>get("ValueString"));
final List<Predicate> filters = new LinkedList<Predicate>();
filters.add(builder.equal(root.join("StockItem").get("id"), vendorNumber));
final List<Predicate> filterNamesCriteria = new LinkedList<Predicate>();
if (filenames.length > 0) {
for (String fileName : filenames) {
filterNamesCriteria.add(builder.like(root.join("ItemValues").<String>get("ValueString"), fileName));
}
filters.add(builder.or(filterNamesCriteria.toArray(new Predicate[0])));
}
query.where(filters.toArray(new Predicate[0]));
final TypedQuery<String> resolvedQuery = this.entityManager.createQuery(query);
return resolvedQuery.getResultList();
I want the result to return a List of Strings (valueString column), but it's not returning anything.
Am I doing something wrong? When I say "builder.createQuery(String.class)", is that correct?
I found the problem:
filters.add(builder.equal(root.join("StockItem").get("id"), vendorNumber));
I was joining based on the StockItem id and not the StockItem.itemNumber
I used two queries to solve the issue of joining the Itemvalues map (it was returning 32,000+ results)