I am trying to write a query like the below on unrelated entities A and B
Select a.x,a.y,a.z FROM A a ,B b Where
b.Parameter_Name='APPLICABLE_RULE_TYPE' And b.Parameter_KEY='MC' AND
b.Parameter_Value=a.rule_type And a.Rule_Status='ON' Order By Rule_Priority;
I am not able to figure out how this should be written in the Repository class of a Spring boot application.
Can someone please suggest a way do this
Thanks in advance.
Edit:
I have tried it as a native query like
#Query(value = "Select Rule_Id, Rule_Sql,S_System,S_Entity, s_table_name,Rule_Sql_Type "
+ "FROM rule_master TRM ,T_SYSTEM_CONFIG TSC Where"
+ " Tsc.Parameter_Name='APPLICABLE_RULE_TYPE' "
+ " And Tsc.Parameter_KEY= :systemType"
+ " AND Tsc.Parameter_Value=trm.rule_type "
+ " And Rule_Status='ON'"
+ " Order By Rule_Priority", nativeQuery = true)
public List<RuleMaster> findByRuleStatus(#Param("systemType" String systemType);
but getting this error
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 17006, SQLState: null
o.h.engine.jdbc.spi.SqlExceptionHelper : Invalid column name
org.springframework.orm.jpa.JpaSystemException: could not execute query; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query
I was able to solve this by using native query itself.
The error was because i was selecting only part of the columns from the table. Instead i have used the below query which works fine:
#Query(value = "Select * "
+ "FROM rule_master TRM ,T_SYSTEM_CONFIG TSC Where"
+ " Tsc.Parameter_Name='APPLICABLE_RULE_TYPE' "
+ " And Tsc.Parameter_KEY= :systemType"
+ " AND Tsc.Parameter_Value=trm.rule_type "
+ " And Rule_Status='ON'"
+ " Order By Rule_Priority", nativeQuery = true)
public List<RuleMaster> findByRuleStatus(#Param("systemType" String systemType);
Related
I have a native query like the following one:
#Query(value = "SELECT * FROM (" +
" SELECT result.*, ROWNUM rn FROM (" +
" SELECT tmp.* FROM (" +
" SELECT " +
" e.id, " +
" e.employee_number, " +
" d.name, " +
" d.surname " +
" FROM employee e INNER JOIN detail d ON e.id_detail = d.id " +
" WHERE e.status = :status " +
" ) tmp " +
" ORDER BY :sortColumn :sortDirection " +
" ) result " +
" WHERE ROWNUM <= (:pageIndex + :pageSize) " +
") " +
"WHERE rn > :pageIndex "
, nativeQuery = true)
ArrayList<Object> getEmployeeDetails( #Param("status") EmployeeStatus status,
#Param("pageSize") int pageSize,
#Param("pageIndex") int pageIndex,
#Param("sortDirection") String sortDirection,
#Param("sortColumn") String sortColumn);
and I'm getting the following errors:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
// ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
// ...
Caused by: java.sql.SQLSyntaxErrorException: ORA-01745: invalid host/bind variable name
What I tried is different return type (and didn't manage to find out which one to use eventually), inserting params with #Param() annotations.
The query itself does work - I tried it directly in the database, but I'm experiencing problems with handling it in Spring.
The query itself for easy debugging:
SELECT * FROM (
SELECT result.*, ROWNUM rn FROM (
SELECT tmp.* FROM (
SELECT
e.id,
e.employee_number,
d.name,
d.surname
FROM employee e INNER JOIN detail d ON e.id_detail = d.id
WHERE e.status = 'status'
) tmp
ORDER BY tmp.name desc
) result
WHERE ROWNUM <= (0 + 5)
)
WHERE rn > 0
EDIT:
I've updated the question with comment suggestions of removing all of the \n's and checking for missing whitespaces.
Plain query, without using any parameters also work, but as I start to insert parameters through #Param() annotations or binds (?1) it stops working giving the errors I updated above.
if EmployeeStatus is enum you have to use this in your query
WHERE e.status = :#{#status.name()}
I am stuck at the moment while trying to write the next query as a spring-data JPA query:
with recursive s as (
select *
from t
where file_id = '12345'
union all
select dfs.*
from t dfs
join s on s.file_id = dfs.parent_folder_id
)
select * from s;
I have tried the next:
#Query(value = "with recursive subfiles as (
select * from t where file_id=?1
union all
dfs.* from t dfs join subfiles s
on s.file_id = dfs.parent_folder_id)
select file_id from subfiles", nativeQuery = true)
But I get the next error:
Method threw 'org.springframework.dao.InvalidDataAccessResourceUsageException' exception.
could not extract ResultSet; SQL [n/a]
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.postgresql.util.PSQLException: ERROR: syntax error at or near "dfs"
The query should list all direct or indirect dependent children for a specific id. (a similar post here)
I have managed to fix it using the next format:
#Query(nativeQuery = true,
value = "with recursive subfiles as " +
"(select * " +
"from t " +
"where file_id=?1 " +
"union all " +
"select dfs.* " +
"from t dfs " +
"join subfiles s " +
"on s.file_id = dfs.parent_folder_id) " +
"select file_id from subfiles")
List<String> listAllByParentId(String folderId);
I'm trying to make a native query request through spring JPA Query annotation using Spacial data types.
The query works perfectly when asked to execute through the console or even in the database.
But when he is asked to be used through Spring.
Does anyone know what I'm doing wrong? or there is a better way to achieve the same result (leaving all the calculations DB sided)?
Thank you in advance
This is the query I'm trying to execute. Again, it works through console but fails to execute through spring boot request
#Query(value = "SELECT TOP 1 * FROM Vehicles v " +
"JOIN Bikelots l ON l.BikeLotId = v.BikeLotId " +
"JOIN BikeTypes b ON b.BikeTypeId = l.BikeTypeId " +
"WHERE b.BikeTypeId = ?1 " +
"ORDER BY " +
"Geography::STGeomFromText(v.Point.MakeValid().STAsText(),4326) " +
".STDistance(Geography::STGeomFromText(Geometry::Point(?2,?3,4326).MakeValid().STAsText(),4326)) "
, nativeQuery = true)
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'Geography:'.
Im using this dialect in application.properties
spring.jpa.database-platform=org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect
The given error was caused because jpa hibernate recognizes the character ":" as a placeholder for an upcoming variable.
By placing the query in a String variable, then adding "\\" before each ":" and assigning the string to the value of #Query, solved the problem. See code for example
String query = "SELECT TOP 1 * FROM Vehicles v " +
"JOIN Bikelots l ON l.BikeLotId = v.BikeLotId " +
"JOIN BikeTypes b ON b.BikeTypeId = l.BikeTypeId " +
"WHERE b.BikeTypeId = ?1 " +
"ORDER BY " +
"Geography\\:\\:STGeomFromText(v.Point.MakeValid().STAsText(),4326) " +
".STDistance(Geography\\:\\:STGeomFromText(Geometry\\:\\:Point(?2,?3,4326).MakeValid().STAsText(),4326)) ";
#Query(value = query, nativeQuery = true)
Unable to pass named parameters in #NamedNativeQuery in spring data jpa
my repo:
#Query(value = "select stat.desc as desc," +
" stat.priority as priority," +
" (case when sum(activeUser) is null then 0 else sum(activeUser) end) as activeUser," +
" (case when sum(totalUser) is null then 0 else sum(totalUser) end) as totalUser" +
" from lookup.user stat left outer join" +
" (" +
" select user.role as role, " +
" sum (case when user.STATUS = 'ACTIVE' then 1 else 0 end) as activeUser," +
" count(*) as totalUser," +
" user.group as group" +
" from Ctrl.user user" +
" where user.group =:userGroup " +
" and user.branch_code =:branchCode " +
" group by user.role,user.group" +
" ) as tbl on stat.role = tbl.role and stat.group = tbl.group" +
" where stat.group =:userGroup " +
" group by stat.desc, stat.priority" +
"", nativeQuery = true)
public List<com.cimb.dto.UserStatusSummary> getSummaryReport(#Param(value = "userGroup") String userGroup, #Param(value = "branchCode") String branchCode);
The underlying database is DB2
When I tried to access that method I am hitting following error.
DB2 SQL Error: SQLCODE=-302, SQLSTATE=22001, SQLERRMC=null, DRIVER=4.25.13
if I hard code those named parameters with values then it's working.
I can not use jpql as real queries have some subqueries in it, so I cant use JPQL
Edit Update
After some digging, I have found out that, the parameters I am passing are in the subquery, since JPA don't have subquery concept it's not injecting into named parameters which resulting in a syntax error.
Now how to work with Subqueries in JPA
Please help.
I have a case similar to the one described in this question, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.
My query:
#NamedQuery(
name = "findRankingsBetween",
query = "SELECT rt FROM Rankingtable rt " +
"INNER JOIN " +
"(SELECT teamId, MAX(lastupdate) as MaxDateTime " +
"FROM Rankingtable " +
"GROUP BY teamId) grouped " +
"ON rt.teamId = grouped.teamId " +
"AND rt.lastupdate = grouped.MaxDateTime " +
"WHERE rt.lastupdate BETWEEN :from AND :to"
)
Error:
Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79
How to write the query properly in jpql?
As noted in this answer, a subquery in JPQL can only occur in select and where clauses.
Hibernate doc.
An equivalent query in JPQL is:
"SELECT rt FROM Rankingtable rt " +
"WHERE rt.lastupdate = (SELECT MAX(r2.lastupdate) " +
"FROM Rankingtable r2 " +
"WHERE r2.teamid = rt.teamid) " +
"AND rt.lastupdate BETWEEN :from AND :to"