JPA query error - java

I just started working with the JAVA jpa. So far I only tried the persist method which works.
I am having trouble running the following query
Customer = Customer(manager.createQuery("Select c FROM Customer c where c.LastName=\"Lname\""));
However in the above case my Customer class is not being recognized. Am I doing this right ?

The query object cannot be typecast-ted so I resolved the problem by using
query = em.createQuery( "SELECT c FROM Country c WHERE c.name = 'Canada'");
Country c = (Country)query.getSingleResult();

Related

Day from date EXTRACT(DAY,s.date) is not working jpa and eclipseLink

I have JPA2 and EclipseLink 2.7.3 i am unsing folloing eclipseLink version documentation the EXTRACT FUNCTION but it is not working
https://www.eclipse.org/eclipselink/documentation/2.7/jpa/extensions/jpql.htm#CHDJGBFJ
#NamedQuery(name = User.FIND_USER_CWC_ERROR_TODAY,
query = "select u from User u,Score s where u.id =s.userId and s.status=com.model.Status.ERROR and s.scoreType = com.model.ScoreType.CREDIT and EXTRACT(DAY,s.lastExecutionDate) = EXTRACT(DAY,CURRENT_DATE) ")
The identification variable 'EXTRACT' is not defined in the FROM clause.
I really do not understand the error
I really don't know why it is not working but i found a workaround
select u from User u,Score s where u.id =s.userId and s.status=com.model.Status.ERROR
and s.scoreType = com.model.ScoreType.CREDIT and FUNC('DAY',s.lastExecutionDate) =
FUNC('DAY',CURRENT_DATE)
It is working like that

Hibernate spatial query exception, but in the postgres console is working

I'm trying to execute this query in my Java code, using Hibernate and Hibernate Spatial:
Query q = s.createQuery("SELECT c FROM crimes c WHERE ST_DWITHIN(ST_MakeLine(ARRAY['SRID=4326;POINT(-49.30621000000001 -25.515020000000003)','SRID=4326;POINT(-49.30619 -25.515770000000003)','SRID=4326;POINT(-49.306180000000005 -25.5162)','SRID=4326;POINT(-49.305780000000006 -25.5162)']), c.location, 0.0001) = true;");
But, this query causes an Exception:
e = (org.hibernate.hql.internal.ast.QuerySyntaxException) org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE_BRACKET, found ',' near line 1, column 151 [SELECT c FROM com.safecity.server.db.model.EntityCrime c WHERE ST_DWITHIN(ST_MakeLine(ARRAY['SRID=4326;POINT(-49.305820000000004 -25.515330000000002)','SRID=4326;POINT(-49.306200000000004 -25.515340000000002)','SRID=4326;POINT(-49.30619 -25.515770000000003)','SRID=4326;POINT(-49.306180000000005 -25.5162)','SRID=4326;POINT(-49.305780000000006 -25.5162)']), c.location, 0.0001) = true]
I checked the query, and I cannot find the error. But, if I get this same query and execute on postgres console, the query is executed without any error and returns the correct value.
Please, someone can help me?
Thanks.
You are using native query here in hibernate. For this you have to use the query as below:
Query q = s.createSQLQuery("SELECT c FROM crimes c WHERE ST_DWITHIN(ST_MakeLine(ARRAY['SRID=4326;POINT(-49.30621000000001 -25.515020000000003)','SRID=4326;POINT(-49.30619 -25.515770000000003)','SRID=4326;POINT(-49.306180000000005 -25.5162)','SRID=4326;POINT(-49.305780000000006 -25.5162)']), c.location, 0.0001) = true;");
Use createSQLQuery() instead of createQuery(), if you want to create a db native query instead of HQL.
I solved this problem changing the query, for this one:
Query q = s.createQuery("SELECT c FROM crimes c WHERE ST_DWITHIN(ST_GeomFromText('LINESTRING(-49.305820000000004 -25.515330000000002,-49.306200000000004 -25.515340000000002,-49.30619 -25.515770000000003,-49.306180000000005 -25.5162,-49.305780000000006 -25.5162)', 4326), c.location, 0.0001) = true");
I don't know why, but it works.
Thanks for the help.
I have seen similar problems with ARRAY constructors in Hibernate before.
PostgreSQL: Issue with passing array to procedure
Replace with an array literal (and optionally a type cast) to make it work. A simple string literal will avoid various complications in the communication.
You are using the PostGis function ST_MakeLine() taking an array of geometry as input parameter.
geometry ST_MakeLine(geometry[] geoms_array)
So:
Query q = s.createQuery(
"SELECT c FROM crimes c
WHERE ST_DWITHIN(ST_MakeLine('{SRID=4326;POINT(-49.30621000000001 -25.515020000000003)
,SRID=4326;POINT(-49.30619 -25.515770000000003)
,SRID=4326;POINT(-49.306180000000005 -25.5162)
,SRID=4326;POINT(-49.305780000000006 -25.5162)}'::geometry[]), c.location, 0.0001)");
This would also explain why your alternative answer providing a linestring (as string literal!) works as well.
Also simplified the boolean expression in the WHERE clause like I commented. Appending = true is just noise.

JPA - My Named Query won't work

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)

Executing hibernate template's findByNamedQuery

I'm pretty new to hibernate and I was trying it out in one of my applications. I chose to use annotation session factory bean and my editor generated entity classes for each table from the DB which had named queries. hibernateTemplate.findByAll worked fine. But when I tried hibernateTemplate.findByNamedQuery("findById", "<some_id>"), it gave an error: java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based. After a bit of googling, tried out multiple solutions:
Changed the namedQuery that was generated by editor from : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = :id"), to : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = ?") but got the same error.
Tried using hibernateTemplate.findByNamedParam but ended up getting error: java.lang.IllegalArgumentException: node to traverse cannot be null!
I can use hibernateTemplate.find() to achieve this but how do I use findByNamedQuery/Param methods to achieve the same since the documentation says these methods may be used to fetch records based on a field?

Convert MySql query to JPA named query

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.

Categories