How to write Subqueries with In-Expressions in JPA 2.0, Criteria API?

Below is the pseudo-code for using sub-query using Criteria API. CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(); Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class); Path<Object> path = from.get(“compare_field”); // field to map with sub-query from.fetch(“name”); from.fetch(“id”); CriteriaQuery<Object> select = criteriaQuery.select(from); Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class); Root fromProject = subquery.from(PROJECT.class); subquery.select(fromProject.get(“requiredColumnName”)); // field to map with main-query subquery.where(criteriaBuilder.and(criteriaBuilder.equal(“name”,name_value),criteriaBuilder.equal(“id”,id_value))); select.where(criteriaBuilder.in(path).value(subquery)); … Read more

How can I recreate this complex SQL Query using NHibernate QueryOver?

I have manage to achieve such dynamic search criterion by using Criteria API’s. Problem I ran into was duplicates with inner and outer joins and especially related to sorting and pagination, and I had to resort to using 2 queries, 1st query for restriction and using the result of 1st query as ‘in’ clause in … Read more

When to use SQL sub-queries versus a standard join?

Subqueries are usually fine unless they are dependent subqueries (also known as correlated subqueries). If you are only using independent subqueries and they are using appropriate indexes then they should run quickly. If you have a dependent subquery you might run into performance problems because a dependent subquery typically needs to be run once for … Read more

How do I concatenate strings from a subquery into a single row in MySQL?

by using the GROUP_CONCAT() function and a GROUP BY call. here’s an example query SELECT p.package_id, p.package_name, p.price, GROUP_CONCAT(pz.zone_id SEPARATOR ‘,’) as zone_list FROM package p LEFT JOIN package_zone pz ON p.package_id = pz.package_id GROUP BY p.package_id you should still be able to order by zone_id s (or zone_list), and instead of using LIKE, you … Read more