Is there a way to further restrict a join by adding some expressions? With plain sql i write:
SELECT c.*, COUNT(i.id) invoice_count
FROM customers c
LEFT JOIN invoices i ON i.customer_id = c.id
AND i.creation_time >= '2012-01-01' -- <= extra restriction
AND i.creation_time < '2013-01-01' -- <= extra restriction
GROUP BY c.id
I haven't found a way to implement this with JPA 2.0 CriteriaQuery.
Update: As requested my (simplified) code so far (without the extra restriction):
CriteriaQuery<CustomerAndInvoiceCount> criteriaQuery = criteriaBuilder.createQuery(CustomerAndInvoiceCount.class);
Root<Customer> customer = criteriaQuery.from(Customer.class);
ListJoin<Customer, Invoice> invoices = customer.join(Customer_.invoices, JoinType.LEFT);
criteriaQuery.select(criteriaBuilder.construct(
CustomerAndInvoiceCount.class,
customer,
criteriaBuilder.count(invoices)));
criteriaQuery.groupBy(customer);
You should just be able to add the criteria predicates without worrying if they are part of the ON clause or the WHERE clause.
Related
I have been trying to get Hibernate to generate me a query with a subquery in its where clause. I've used this answer as a base to help me going, but this question mentioned only one table.
However, this is what I would need (in SQL):
SELECT [...]
FROM a
LEFT OUTER JOIN b on a.idb = b.idb
LEFT OUTER JOIN c on b.idc = c.idc
[...]
LEFT OUTER JOIN k out on j.idk = k.idk
WHERE k.date = (SELECT max(date) from k in where in.idk = out.idk) OR k.date is null
As I am not very used to using Hibernate, I'm having trouble specifying these inner joins while navigating in the inner constraints.
I was able to re-create the initial criteria as in the linked answer, but I can't seem to join the criteria and the rootCriteria.
If the entities are properly joined with #ManyToOne annotations, simply joining the criteria to the previous table will be enough to propagate the criteria to the whole query.
The following code seems to work properly to add the WHERE clause I'm looking for.
DetachedCriteria kSubquery = DetachedCriteria.forClass(TableJPE.class,"j2");
kSubQuery = kSubQuery.createAlias("k","k2");
kSubQuery.setProjection(Projections.max("k2.date"));
kSubQuery = kSubQuery.add(Restrictions.eqProperty("j.id", "j2.id"));
rootCriteria.add(Restrictions.disjunction()
.add(Subqueries.propertyEq("k.date",kSubQuery))
.add(Restrictions.isNull("k.date")));
I am just wondering if it is allowed in Hibernate to use the same DetachedCriteria object within one Criteria multiple times. Imagine the following case:
DetachedCriteria dCriteria = DetachedCriteria.forClass(A.class)
.add(Restrictions.eq("id", 1))
.setProjection(Projections.property("id"));
Criteria criteria = session.createCriteria(B.class)
.add(
Restrictions.or(
Restrictions.and(
Subqueries.exists(dCriteria),
Restrictions.eq("id", 1)
),
Restrictions.and(
Subqueries.notExists(dCriteria),
Restrictions.eq("id", 2)
)
)
.setProjection(Projections.property("id"));
Is the usage of dCriteria twice within the this criteria allowed? It seems to work but i am not sure if it might lead to problems in more complex cases (maybe the DetachedCriteria saves same state information during query generation?). I already did some reasearches but i couldn't find an explicit answer.
No it isn't (always) safe to re-use DetachedCriteria. For example: get a list and a rowcount, reusing the DetachedCriteria:
DetachedCriteria dc = DetachedCriteria.forClass(A.class);
Criteria c1 = dc.getExecutableCriteria(session);
c1.setProjection(Projections.rowCount());
long count = ((Number) c1.uniqueResult()).longValue();
System.out.println(count + " result(s) found:");
Criteria c2 = dc.getExecutableCriteria(session);
System.out.println(c2.list());
This prints:
Hibernate: select count(*) as y0_ from A this_
4 result(s) found:
Hibernate: select count(*) as y0_ from A this_ <-- whoops
[4] <-- whoops again
Really simple things that don't alter the DetachedCriteria might be safe, but in general wrap the generation in some kind of factory and re-generate them each time you need them.
Officially, cloning DetachedCriteria on each call to getExecutableCriteria will never happen. See their issues, particularly HHH-635 and HHH-1046 where Brett Meyer states: "The Criteria API is considered deprecated", and the developers guide (v4.3 §12) which states:
Hibernate offers an older, legacy org.hibernate.Criteria API which should be considered deprecated. No feature development will target those APIs. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery.
EDIT: In your example you re-use the same DetachedCriteria inside the same query. The same caveats therefore apply - if you, for instance, use setProjection with one of the uses, things go wrong with the second use. For example:
DetachedCriteria dCriteria = DetachedCriteria.forClass(A.class)
.add(Restrictions.eq("id", 1))
.setProjection(Projections.property("id"));
Criteria criteria = session.createCriteria(B.class)
.add(
Restrictions.or(
Restrictions.and(
Subqueries.exists(dCriteria
.add(Restrictions.eq("text", "a1")) // <-- Note extra restriction
.setProjection(Projections.property("text"))), // <-- and projection
Restrictions.eq("idx", 1)
),
Restrictions.and(
Subqueries.notExists(dCriteria),
Restrictions.eq("idx", 2)
)
))
.setProjection(Projections.property("id"));
Object o = criteria.list();
This yields the SQL:
select this_.idx as y0_ from B this_
where (
(exists
(select this_.text as y0_ from A this_ where this_.id=? and this_.text=?) and this_.idx=?)
or (not exists
(select this_.text as y0_ from A this_ where this_.id=? and this_.text=?) and this_.idx=?))
We didn't ask for the text=? part of the not exists, but we got it due to the re-use of the DetachedCriteria †
† This leads to bad situations where, if you applied the .add(Restrictions.eq("text" ... to both uses of dCriteria, it would appear twice in both the exists and not exists in the SQL
I have duplicate in result in hibernate query, such as:
select new ValueObject(h.id, c.firstName, c.lastName)
from HistoryTable as h left join CustomerTable as c
where h.customerId = c.id and c.notDeleted
order by c.firstName, c.lastName
But, when i used DISTINCT, duplicate in result continue to appear
select distinct new ValueObject(h.id, c.firstName, c.lastName)
from HistoryTable as h left join CustomerTable as c
where h.customerId = c.id and c.notDeleted
order by c.firstName, c.lastName
But my question is, if there is any possibility to using DISTINCT for excluding duplicates for creating new ValueObject in HSQLDB query?
Hibernate does not return distinct results for a query with left or right join.
You can use Hiberante setResultTransformer for your purposes. For more detail's explanations, why and how it resolve, look:
https://developer.jboss.org/wiki/HibernateFAQ-AdvancedProblems#jive_content_id_Hibernate_does_not_return_distinct_results_for_a_query_with_outer_join_fetching_enabled_for_a_collection_even_if_I_use_the_distinct_keyword
and
How do you create a Distinct query in HQL
Is it possible to query "UNION" in JPA and even "Criteria Builder"?
I'm looking for examples, but so far i got no result.
Does anyone have any examples of how to use it?
Or would that be with native sql?
SQL supports UNION, but JPA 2.0 JPQL does not. Most unions can be done in terms of joins, but some can not, and some are more difficult to express using joins.
EclipseLink supports UNION.
Depending on the case, one could use sub queries, something like:
select e
from Entity e
where e.id in
(
select e.id
from Entity2 e2
join e2.entity e
where e2.someProperty = 'value'
)
or e.id in
(
select e.id
from Entity3 e3
join e3.entity e
where e3.someProperty = 'value2'
)
One thing just comes to my mind (searching for the exact same problem):
Perform two different JPA queries on the same entity mapping and simply add the objects of the second result to the list (or set to avoid duplicates) of the first result.
That way you get the same effect as with a UNION, the difference being that you use two SQL statements instead of one. But actually, I would expect that to perform just as good as issueing one UNION statement.
write native query (set it true , default its false) - ex.
String findQuery = "select xyz from abc union select abc from def"
#Query(value = findQuery, nativeQuery = true)
//method
using EntityManager.createNativeQuery(...);
It's allow you use UNION
There is no direct union for JPA, what I did was to build two specifications.
Specification<Task> specification = Specification.where(null);
Specification<Task> specification2 = Specification.where(null;
They belong to a single table but return different values
specification = specification.and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(criteriaBuilder.function(MONTH, Integer.class, root.get("deliveryExpirationDate")), month));
specification2 = specification2.and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.lessThan(criteriaBuilder.function(MONTH, Integer.class, root.get("deliveryExpirationDate")), month))
.and((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("enable"), true));
for this example it is a table of tasks that in the first specification I need the tasks of the current month enabled and disabled, and in the second specification I only need the tasks enabled of the previous months.
Specification<Task> specificationFullJoin = Specification.where(specification).or(specification2);
Esto es muy útil para que la lista de tareas devueltas tenga paginación.
taskRepository.findAll(specificationFullJoin, pageable).map(TaskResponse::new); //Here you can continue adding filters, sort or search.
It helps me a lot, I hope it is what they are looking for or that it serves them something.
I have solved this in my project.
Union/Union All will work if you change it to native query and use like below
//In Your Entity class
#NamedNativeQuery(name="EntityClassName.functionName",
query="your_native_query")
//In your Repository class
#Query(native=true)
List<Result> functionName();
Below method of defining Native query in JPA repository will not solve this problem
#Query(value="your_native_query", native=true)
will not
You can directly use UNION in your query.
The following query returns id of friends from FRIENDSHIP table.
Eg:
TypedQuery<String> queryFriend = em.createQuery("SELECT f.Id FROM Friendship f WHERE f.frStuId = :stuId UNION "
+ "SELECT f.frStuId FROM Friendship f WHERE f.FriendId = :stuId", String.class);
queryFriend.setParameter("stuId", stuId);
List<String> futureFriends = queryFriend.getResultList();
I'm trying to write a HQL/Criteria/Native SQL query that will return all Employees that are assigned to a list of Projects. They must be assigned to all Projects in order to be selected.
An acceptable way of achieving this with native SQL can be found in the answer to this question: T-SQL - How to write query to get records that match ALL records in a many to many join:
SELECT e.id
FROM employee e
INNER JOIN proj_assignment a
ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
GROUP BY e.id
HAVING COUNT(*) = [size of list of project ids]
However, I want to select all fields of Employee (e.*). It's not possible to define SQL grouping by all the columns(GROUP BY e.*), DISTINCT should be used instead. Is there a way to use DISTINCT altogether with COUNT(*) to achieve what I want?
I've also tried using HQL to perform this query. The Employee and ProjectAssignment classes don't have an association, so it's not possible to use Criteria to join them. I use a cross join because it's the way to perform a Join without association in HQL. So, my HQL looks like
select emp from Employee emp, ProjectAssignment pa
where emp.id = pa.empId and pa.paId IN :list
group by emp having count(*) = :listSize
However, due to a bug in Hibernate, GROUP BY entity does not work. The SQL it outputs is something like group by (emptable.id).
Subquerying the assignment table for each project (dynamically adding and exists (select 1 from proj_assignment pa where pa.emp_id=e.id and pa.proj_id = [anId]) for each project in the list) is not an acceptable option.
Is there a way to write this query properly, preferrably in HQL (in the end I want a List<Employee>), without modifying mappings and without explicitly selecting all columns in the native SQL ?
EDIT: I'm using Oracle 10g and hibernate-annotations-3.3.1.GA
How about:
select * from employee x where x.id in(
SELECT e.id
FROM employee e
INNER JOIN proj_assignment a
ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
GROUP BY e.id
HAVING COUNT(*) = [size of list of project ids]
)
I've found an alternative way to achieve this in HQL, it's far more inefficient than what I'd like, (and than what is really possible without that nasty bug) but at least it works. It's better than repeating subselects for each project like
and exists (select 1 from project_assignment pa where pa.id = someId and pa.emp_id = e.id)
It consists of performing a self-join subquery in order to find out, for each of the Employees, how many of the projects in the list they are assigned to, and restrict results to only those that are in all of them.
select e
from Employee
where :listSize =
(select distinct count(*)
from Employee e2, ProjectAssignment pa
where
e2.id = pa.id_emp and
e.id = e2.id
and pa.proj_id IN :projectIdList
)