Native query not working in hibernate - postgresql

I have an issue with my native query.
I've got:
#Query(value="SELECT * from orders where orders.house in ((:houseArray))", nativeQuery = true)
List<Order> findByHouseId(#Param("houseArray") List<Long> houseArray);
And when I am trying to execute, I get the following:
2017-04-18 14:19:49,736 DEBUG org.hibernate.SQL: SELECT * from orders where orders.house in ((?, ?, ?, ?, ?))
2017-04-18 14:19:49,737 TRACE o.h.t.d.s.BasicBinder: binding parameter [2] as [BIGINT] - [4]
2017-04-18 14:19:49,737 TRACE o.h.t.d.s.BasicBinder: binding parameter [3] as [BIGINT] - [5]
2017-04-18 14:19:49,737 TRACE o.h.t.d.s.BasicBinder: binding parameter [1] as [BIGINT] - [3]
2017-04-18 14:19:49,737 TRACE o.h.t.d.s.BasicBinder: binding parameter [4] as [BIGINT] - [6]
2017-04-18 14:19:49,737 TRACE o.h.t.d.s.BasicBinder: binding parameter [5] as [BIGINT] - [7]
2017-04-18 14:19:49,738 ERROR o.h.e.j.s.SqlExceptionHelper: ERROR: operator does not exist: bigint = record
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Position: 49
2017-04-18 14:19:49,756 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet]: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = record
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
However, if I run the following query in console:
SELECT * from orders where orders.house in (1,15,2,4,5,3,6,7);
It returns proper list of orders.
How can I fix this?

Try removing one set of brackets from ((:houseArray)) so it looks like that:
#Query(value="SELECT * from orders where orders.house in (:houseArray)", nativeQuery = true)
List<Order> findByHouseId(#Param("houseArray") List<Long> houseArray);
(value, value, value) is a record, so when you do column in ((value, value, value)) you compare column vs record.

Related

DB2 Assign result of with clause to variable

I am using DB2 LUW and want to a assign a result of a With clause to a variable in a stored procedure.
I got the exception
{0:0} An unexpected token "AS" was found following "l = (WITH BASE". Expected tokens may include: "JOIN".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.28.11
Is it possible to assign the result on this way or should I have to solve it with a cursor?
DECLARE result CLOB(8M);
SET result = (WITH BASE AS (
xxx
)
SELECT JSON_ARRAY (select json_objects FROM ITEMS format json) FROM SYSIBM.SYSDUMMY1);
Use instead the syntax style:
with ctename AS ( ... ) SELECT ... INTO ... FROM ctename;

JPA jsonb query issue with positional argument

I'm having an issue with JPA and json querying. My JPA is Eclipselink and I use Postgres DB.
My query is
with values as(select id, inputspecifications as spec from process where commercial = True and inputspecifications #> '[{\"type\":\"raster\"}]') select id from values where (spec -> 'platforms' is null or (spec -> 'platforms' -> 'satellites' is not null and (spec -> 'platforms' -> 'satellites' ?& array['310802']))
The query works fine until the array inclusion comparison (last bit). It seems JPA is seeing ?& as a positional argument, as per the fine logs
[EL Warning]: sql: 2022-11-07 10:22:05.336--ServerSession(65586123)--Missing Query parameter for named argument: & "null" will be substituted.
[EL Fine]: sql: 2022-11-07 10:22:05.336--ServerSession(65586123)--Connection(1463355115)--with values as(select id, inputspecifications as spec from process where commercial = True and inputspecifications #> '[{"type":"raster"}]') select id from values where (spec -> 'platforms' is null or (spec -> 'platforms' -> 'satellites' is not null and (spec -> 'platforms' -> 'satellites' ? array['310802']))
bind => [null]
[EL Fine]: sql: 2022-11-07 10:22:05.343--ServerSession(65586123)--SELECT 1
[EL Warning]: 2022-11-07 10:22:05.344--UnitOfWork(446445803)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.6.v20200131-b7c997804f): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 293
Error Code: 0
I have tried escaping in various ways, ie \?&, \?\&,... all fail one way or another...
Any idea how to make jpa NOT see ?& as a positional parameter?

Spring boot cannot find postgresql function (data type mismatch)

Developed a function. I've moved all the sql codes I've written on the Java side here.
In the function I have created, the first and second parameters are waiting for big integer type data. I am trying to send the long-defined data on the spring boot side to big integer and send it to this function. In the mean time, it gives me the error of "org.hibernate.exception.SQLGrammarException". I mentioned the error contents below.
ERROR 21952 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Error calling CallableStatement.getMoreResults] with root cause
org.postgresql.util.PSQLException: ERROR: function fn_subscriber_to_iservice(numeric, numeric, character varying, character varying, double precision, double precision, double precision, numeric, numeric, bytea) does not exist
İpucu: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 15
The function is as follows.
CREATE OR REPLACE FUNCTION "public"."fn_subscriber_to_iservice"("_service_id" int8, "user_id" int8, "_start_date" varchar, "_end_date" varchar, "total_price" float8, "total_month" float8, "price_per_person" float8, "_start_station_id" int8, "_end_station_id" int8, "passengerlist" "public"."_passengers_array")
The Spring boot codes
StoredProcedureQuery subscriber = entityManager.createStoredProcedureQuery("fn_subscriber_to_iservice");
subscriber.registerStoredProcedureParameter(1, BigInteger.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(2, BigInteger.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(3, String.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(4, String.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(5, Double.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(6, Double.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(7, Double.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(8, BigInteger.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(9, BigInteger.class, ParameterMode.IN);
subscriber.registerStoredProcedureParameter(10, List[].class, ParameterMode.IN);
subscriber.setParameter(1, BigInteger.valueOf(payload.getService_id()));
subscriber.setParameter(2, BigInteger.valueOf(userDetail.getId()));
I expect your help on this. Thanks

Database fragment query error "parameters must be of length 0 for query"

I am trying to query a json array in the building table, jsonb metadata column, and within google_place_ids property, which is an array.
Elixir is giving me an error:
Here's the query the fragment is generating:
SELECT b0."id", b0."base_sku", b0."name", b0."logo", b0."email", b0."active", b0."sync", b0."building_group_id", b0."operating_region_id", b0."building_package_id", b0."metadata", b0."location", b0."inserted_at", b0."updated_at" FROM "buildings" AS b0 WHERE (b0."metadata"->'google_place_ids' #> '["$1"]') AND (b0."active" = TRUE) ["1234231223123"]
Here's the code:
defp query_by_google_place_id(query, google_place_id) do
from(b in query,
where: fragment("?->'google_place_ids' #> '[\"?\"]'", b.metadata, ^google_place_id),
where: b.active == true,
limit: 1)
end
Here is the error:
[error] #PID<0.1340.0> running Proxy.InstrumentedPlug terminated
Server: localhost:4000 (http)
Request: GET /something/google_place_id/1234231223123
** (exit) an exception was raised:
** (ArgumentError) parameters must be of length 0 for query %Postgrex.Query{columns:
This is not how PostgreSQL will understand it. The problem is that Ecto's fragment do not know anything about SQL (or other query language) you can use there, so it ends treating ? as a query parameter while PostgreSQL treats it as a raw string "$1". What you need to do is to pass string directly in form of:
fragment("?->'google_place_ids' #> ?", b.metadata, ^"[\"#{google_place_id}\"]")
This works, less quotes and no brackets
defp query_by_google_place_id(query, google_place_id) do
from(b in query,
where: fragment("?->'google_place_ids' #> ?", b.metadata, ^google_place_id),
where: b.active == true,
limit: 1)
end

Exception occurs for hash character in Dollar quote with JPA

I am using Dollar quote (i.e. $xx$) for my query and getting Exception when the input has a hash character(#) inside.
select * from tbl_abc where col_x = $xx$#$xx$
^
The Exception is:
Internal Exception: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Error Code: 0
Call: select * from tbl_abc where col_x = $xx$?
bind => [1 parameter bound]
I can see there a ? character in the error message, but I didn't have that in my query. Here is my java code:
String query = "select * from tbl_abc where col_x = $xx$#$xx$";
Query nativeQuery = em.createNativeQuery(query, Abc.class);
List<Abc> abcList = nativeQuery.getResultList();
FYI: it works smoothly when I use '#' instead of $xx$#$xx$. Also my query runs nicely from the postgres console.
How can I escape that # character for Dollar quote from JPA?
I am using Java with Eclipselink and the database is Postgres.