I have a MySql query like this:
select AK.*, max(AA.activityDate)
from AssessmentKey AK
join AssessmentActivity AA on AA.ASSESSMENTKEY_ID = AK.id
group by AK.id having max(AA.activityDate) <= '2012-10-02 17:30:55'
Is there a way to convert into in JPA NamedQuery. I am using OpenJPA.
If I put it directly into:
#NamedQuery(name = "AssessmentActivity.findByDate",
query = "select AK.*, max(AA.activityDate) from AssessmentKey AK
join AssessmentActivity AA on AA.ASSESSMENTKEY_ID = AK.id
group by AK.id having max(AA.activityDate) <= '2012-10-02 17:30:55'")
The error is showed here: select AK.* that identifier expected, got "*" and also it does not like on, here it says:
How can I resolve this problem?
First problem: you should replace AK.* with AK you just need the entity alias here.
Second problem: join syntax is not like that. You should write: join and navigate through the object references,eg: AK.assesmentActivity and use the where keyword instead of on
Here's a tip on join: JPQL join
Remember: you are in the ORM, dealing with Entities and their properties, not DB foreign keys and columns.
(ps: Maybe you wanted to write a NativeQuery? There you can use native SQL syntax)
EDIT:
(on your comment) So you must start your query from AA:
select AK from AssesmentActivity AA join AssesmentKey AK where AA.assesmentKey = AK ...
This way you can join them.
Related
I am using queryDsl-Sql I need to do an update statement with a join clause like:
update MY_TABLE t1 set t1.MY_FIELD = 'SOME_VALUE'
JOIN MY_TABLE_2 t2 ON t1.FIELD_WITH_FK = t2.ID
where t2.OTHER_FIELD=12324556789 AND t2.OTHER_FIELD like '%something%'
Unfortunately, on queryDsl I was only able to do subqueries during update but not joins:
dsl.update(table1)
.set(my_field, "SOME_VALUE")
.where(
field_with_fk.in(
dsl.select(id).from(table2).where(other_field.eq(12324556789))
, fieldName.like("%something%"));
Which is translated to a subquery (as expected) and happens to take much much more time (difference between 10 seconds using joins and more than 1h using subselects)
I have seen that on JPAUpdateClause is possible to do so but I am not using QueryDsl-jpa here. QueryDSL-SQL has only SqlUpdateClause and I was not able to find how to join different tables when using It.
I think this is more a workaround than a solution, but maybe helps
also others:
dsl.update(table1)
.set(field1, myValue)
.addFlag(
QueryFlag.Position.START_OVERRIDE, //it replaces update by update with join
Expressions.stringTemplate("update {0} join {1} on {2} = {3} #", // I need # to ignore table1 otherwise incorrect SQL
table1, table2, table1FieldWithFkToTable2, table2Id))
.where(other_field.eq(12324556789), fieldName.like("%something%"));
this generates the following SQL:
update table1 join table2 on table1FieldWithFkToTable2 = table2Id #table1
set field1 = myValue
where other_field=12324556789 and fieldName like '%something%'
I have two tables that are loosely coupled. I have a SQL query that works, but I am having difficulty converting it to HQL.
Table account has a column 'name', of which a substring is the key to another table.
SELECT
a.id,
a.name
j.description
FROM account a
JOIN jar j ON j.jar_id = substr(a.name, LOCATE('jar-', a.name) + LENGTH('jar-'), LENGTH(a.name))
This join works where account.name has values 'jar-255', 'jar-756', 'jar-881', etc. It extracts the id by substring and uses it to reference the jar table.
It doesn't work in Java/HQL, as the Account object doesn't directly reference or have a child Jar object. The error is
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join!
This is the join in HQL:
JOIN Jar j ON j.jarId = substring(a.name, LOCATE(a.name, 'jar-') + LENGTH('jar-'), LENGTH(a.name))
Is this acheivable?
Prior to Hibernate 5.1 you will need to have a reference/relation to do a join. So if it is an older version (below 5.1), then you will have to do the following:
FROM Account a, Jar j
WHERE j.jarId=substring....
Possible solution for your problem is as follows:
SELECT
a.id,
a.name
j.description
FROM account a
JOIN jar j
ON a.name = concat("jar-",j.jar_id);
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 having some problems, with the first time I've gotten into JPA. This is the query I'd like to put in as an #NamedQuery, and this SQL works.
select t1.*, t2.SHORT_NAME from ePluribusWS.GRAPH_ACL t1 join DB_AUTH.USERS t2 on t1.USER_ID = t2.ID where GRAPH_ID = 31611 ;
I'm not sure if this is supported within JPA, since I'm doing a JOIN across different databases, but within the same server. The SQL works fine.
When I try and add this in as a named query (the third one below) I get an error message (Syntax error parsing) that "A path expression cannot end with a comma" which the only Google'ing of shows me JPA source code which generated the error message.
#Entity
#Table(name = "GRAPH_ACL", catalog = "ePluribusWS", schema = "")
#XmlRootElement
#NamedQueries({
.
.
#NamedQuery(name = "EPluribusACLEntryRecord.findByUserId", query = "SELECT g FROM ACLEntryRecord g WHERE g.userId = :userId"),
#NamedQuery(name = "EPluribusACLEntryRecord.findByGraphId", query = "SELECT t1.*, t2.SHORT_NAME FROM ACLEntryRecord t1 JOIN DB_AUTH.USERS t2 ON t1.USER_ID = t2.ID WHERE t1.GRAPH_ID = :graphId"),
#NamedQuery(name = "EPluribusACLEntryRecord.findByCreated", query = "SELECT g FROM ACLEntryRecord g WHERE g.created = :created"),
I'm sort of confused, since it looked like the JPA annotations required that they end with a comma.
Thanks for taking the time to read my question, and provide any insight. Normally, editors remove this "thanks" section, which I think is sort of an unpleasant edit.
A NamedQuery is JPQL, not SQL. There is no "*" and "DB_AUTH.USERS" is an invalid construct in JPQL ... has to refer to entities relative to the candidate entity (the entity defines where its schema is).
If you wanted to refer to tables that are not mapped to entities then you would have to use an SQL query (NamedNativeQuery)
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
)