Hibernate NamedQuery UPDATE statement throws QuerySyntaxException - java

I encountered a very interesting issue. I want to create an UPDATE statement NamedQuery for my class (I know this is a bit hacky).
The weird thing is if I use positioned parameters in the query like ?1, ?2 etc. it works perfectly. However, if I want to use named parameters like :id, it fails with the following error:
failed because of: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting EOF, found 'consumingTxId' near line 1.
I'm using Kotlin btw.
My entity:
class StateDetailEntity(
#Id
#Column(name = "issue_tx_id")
val issueTxId: String,
#Column(name = "consuming_tx_id")
val consumingTxId: String?
)
My named query:
NamedQuery(
name = "StateDetailEntity.consume",
query = "UPDATE StateDetailEntity SET " +
"consumingTxId = :consumingTxId " +
"WHERE issueTxId = :issueTxId " +
"AND consumingTxId IS NULL"
)
If I add an alias to the table and re-write the name query to like UPDATE StateDetailEntity s SET... I get the following error:
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting EOF, found 's'.
The funny thing is if I change the query like this:
NamedQuery(
name = "StateDetailEntity.consume",
query = "UPDATE StateDetailEntity SET " +
"consumingTxId = ?1 " +
"WHERE issueTxId = ?2 " +
"AND consumingTxId IS NULL"
)
There are no issues at all. Any ideas? Using Hibernate 5.4.32.Final.

Related

PostgreSQL NativeQuery with Param - org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

I'm seeing the below error whenever I try and execute a nativeQuery with params.
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
The query being used and repo function is below
private String queryStr = "SELECT * FROM schema1.txn " +
"WHERE stat = 'Shipped' " +
"AND id IN :idList\\:\\:text[] " +
"AND issue_dt < NOW() - :ageToExpire\\:\\:interval";
#Query(value = queryStr, nativeQuery = true)
List<txn> findTxns(
#Param("idList") String idList,
#Param("ageToExpire") String ageToExpire
);
And the findTxns call looks like so
.findTxns("('ID1','ID2','ID3')", "'10 days'")
I'm unsure as to why I'm still seeing the above error. I'm casting the string params to their respective text list and interval types but Postgres doesn't seem to agree with that. I've seen similar issues but I can't seem to get any of the marked resolutions working in my case; I've tried isolating the query to just use one param but that isn't resolving anything.

LIKE COALESCE in Spring JPA does not work

So my problem is the following:
I have a table I want a filter to apply to. This filter should call a query which finds based on the given information the reports.
This is how my query looks:
#Query("SELECT r FROM Report r WHERE r.importanceLevel = COALESCE(importance,'%')" +
"AND r.source = COALESCE(source,'%')" +
"AND r.resolvedStatus = COALESCE(resolvedStatus,'%')" +
"AND r.header LIKE + '%' COALESCE(query,'%') + '%'")
List<Report> getReportsByAppliedFilter(#Param("importance") int importance, #Param("source") String source,
#Param("resolvedStatus") int resolvedStatus, #Param("query") String query);
Problem is: IntelliJ does not like the following:
LIKE + '%' COALESCE(query,'%') + '%'
Error: expected, got +
Do you have any idea how to solve this otherwise?
Yeah, time to go to bed. You dont use + for concat , you use concat():
#Query(value = "SELECT r FROM Report r WHERE r.importanceLevel = COALESCE(importance,'%')" +
"AND r.source = COALESCE(source,'%')" +
"AND r.resolvedStatus = COALESCE(resolvedStatus,'%')" +
"AND r.header LIKE CONCAT('%', COALESCE(query,'%'), '%')")
If your column name is request_status and table name is connections then use COALESCE like
#Query(value = "SELECT connections.id, COALESCE(connections.request_status,'') as request_status.... ", nativeQuery = true)
List<ZXYType> xysfunction();
Here if request_status is null then it will be replaced by an empty string.

JPA Hibernate JOIN ... ON ... AND

I use the following query:
SELECT * FROM phaseinproject as pip JOIN projectinrelease pir
ON pip.projectInRelease_id = pir.id
JOIN releaseperiod as rp ON pir.release_id = rp.id
JOIN releasestructure as rs ON rs.id = rp.releaseStructure_id
JOIN phaseinreleasestructure as pirs ON pirs.releaseStructure_id = rs.id
JOIN releasephase as rlp ON rlp.id = pirs.phase_id
AND rlp.id = pip.phase_id
This query works totally fine. I get three results (the amount I expect).
I convert this query to the following HQL query:
TypedQuery<PhaseInProjectOverview> findPhasesInRelease = em.createQuery("SELECT NEW nl.dashboard.dto.out.PhaseInProjectOverview(phaseInProject.id, phase.name, phaseInProject.startDate, phaseInProject.plannedEndDate, phaseInProject.endDate) FROM PhaseInProject phaseInProject "
+ "JOIN phaseInProject.projectInRelease projectInRelease "
+ "JOIN projectInRelease.release release "
+ "JOIN release.releaseStructure releaseStructure "
+ "JOIN releaseStructure.phaseInReleaseStructures phaseInReleaseStructure "
+ "JOIN phaseInReleaseStructure.phase phase "
+ "WHERE release.id = :releaseId ORDER BY phaseInReleaseStructure.position, phaseInProject.startDate", PhaseInProjectOverview.class);
findPhasesInRelease.setParameter("releaseId", releaseId);
return findPhasesInRelease.getResultList();
No matter what I try: I get 6 results, because HQL does not seem to support the "JOIN ... ON ... AND ..." sql syntax.
Does anyone know how to solve this problem?
edit:
I added my own answer with the used solution. Thank you all for the answers/pointers.
Try the with keyword: phaseInReleaseStructure.phase phase WITH phase.id = phaseInProject.phase_id - this should result in SQL like releasephase as rlp ON rlp.id = pirs.phase_id AND rlp.id = pip.phase_id
Alternatively just add that condition in the where clause:
... WHERE release.id = :releaseId AND phase.id = phaseInProject.phase_id ...
I solved my problem with an extra WHERE clause:
phase.id = phaseInProject.phase.id
Now I get the results I was expecting.
The 'WITH' keyword does not seem to work with multiple entities. When I try, I get an exception:
HQL error: with-clause referenced two different from-clause elements
When trying to use the 'ON' syntax like JOIN phaseInReleaseStructure.phase phase ON phase.id = phaseInProject.id, I get another error:
unexpected token: ON near line 1, column 473

Syntax error in HQL query

I have this code in my dao method:
TypedQuery<Application> query = em.createQuery(
"FROM Application a "
+ "WHERE LOWER(a.candidate.firstName LIKE :firstName) "
+ "OR LOWER(a.candidate.lastName LIKE :lastName) "
+ "OR (a.candidate.phoneNumber LIKE :phoneNumber) "
+ "OR LOWER(a.candidate.email LIKE :email) "
+ "OR LOWER(a.candidate.postcode LIKE :postcode)"
, Application.class);
query = query.setParameter("firstName", candidate.getFirstName());
query = query.setParameter("lastName", candidate.getLastName());
query = query.setParameter("phoneNumber", candidate.getPhoneNumber());
query = query.setParameter("email", candidate.getEmail());
query = query.setParameter("postcode", candidate.getPostcode());
and it throws this Exception:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node: ( near line 1, column 57 [FROM com.xxx.xxx.entity.Application a WHERE LOWER(a.candidate.firstName LIKE :firstName) OR LOWER(a.candidate.lastName LIKE :lastName) OR (a.candidate.phoneNumber LIKE :phoneNumber) OR LOWER(a.candidate.email LIKE :email) OR LOWER(a.candidate.postcode LIKE :postcode)]
Something is probably wrong with my query, but I cannot see what... Any help appreciated.
It's your parenthesis.
LOWER(a.candidate.firstName LIKE :firstName)
should be:
LOWER(a.candidate.firstName) LIKE :firstName
etc.

How can I execute an update (named query) in Hibernate Template?

I have a namedQuery like this:
#NamedQueries ({ ...
#NamedQuery(name = "myUpdate", query = "update User set country = 'EN' where user.id = :id")
...
})
In dao layer
getHibernateTemplate().bulkUpdate(...?)
UPDATE
Query query = sessionFactory.getCurrentSession.getNamedQuery("myUpdate");
getHibernateTemplate.bulkUpdate(query.getQueryString(), id);
I get an error:
Hibernate: update User, set country=EN where id = 2343 ORA-00971: missing SET keyword
Anybody now how can resolve this problem?
UPDATE 2
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.id = ?")
OK
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.name = ?")
NOT OK :(
Unfortunately, that feature is missing in spring, as the named queries are supposed to be used only to retrieve data. One thing you can do is (this is a bit of a work around)
Session session = getHibernateTemplate().getSession();
Query query = session.getNamedQuery("myUpdate");
String update = query.getQueryString();
getHibernateTemplate().bulkUpdate(update, [params]);
I would put that in some kind of helper, so your DAO logic doesn't have to go around spring too.
edit
there's a dangling comma between User and set "update User , set country=EN where"
Actually this is a very old question but I had the same problem today. I realized that the update does not work since you cannont have a join inside of a simple UPDATE. That is also the reason why the comma is added. Hibernate tries to rewrite the query like this:
UPDATE User u, Profile p SET u.country = 'EN' where p.name = ? AND p.id = u.profile.id
To solve the issue you need to select the ids from the second table yourself.
#NamedQuery(name = "myUpdate", query = ""
+ " UPDATE User u "
+ " SET country = 'EN' "
+ " WHERE u.profile.id IN ( "
+ " SELECT p.id "
+ " FROM Profile p "
+ " WHERE p.name = ? "
+ " )"

Categories

Resources