How to query in jsonb postgresql and convert to predicate JPA - java

i have stuck :)
does anyone know how query postgresql in jsonb
i have table USER
INT id,
Varchar name,
jsonb categoryId
the example data in categoryId field like this = [1,2,3,4,5]
I have tried this query which works:
select *
from user where categoryId #> '2'::jsonb ;
but how to query with multiple params like
select *
from user
where categoryId #> '1,3,4'::jsonb
and i will implement this to hibernate jpa/jpql-predicate, but i want to know native query first
Thankyou so much

In SQL you can use the ?| operator for this
select *
from "user"
where categoryid ?| array['1','3','4'];
That will return rows where at least one of the values is contained in the JSON array. If you want to find those that contain all values, use the ?& operator instead.
To use the #> operator you would need to use a JSON array on the right hand side:
select *
from "user"
where categoryid #> '[1,3,4]'::jsonb
Note that user is a reserved keyword. You will have to enclose it in double quotes every time you want to refer to the table. I would highly recommend to find a different table name.

Related

How to using like array of string HIBERNATE

I'm trying to pass an array of string as a parameter to my query but I get the following error
ERROR: operator does not exist: text ~~ record Dica: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Here is my query
select * from table where value like any (array[?1]);
when I run it using hibernate the query is like:
select * from table where value like any (array[('%foo%', '%bar%', '%baz%')]);
There's a best way to pass my array as parameter?? I think that is important to say that my array is dynamic so i can't fiz it in my query.
use setParameterList method.
String queryStr = "select * from table where value in :valueList";
Query query = SessionFactory.getCurrentSession().createQuery(queryStr);
query.setParameterList("valueList", new Object[]{"%foo%","%bar%","%baz%"});
Please note that I used in clause and it doesn't support wildcard characters such as %.
First use createNativeQuery instead of createQuery as syntax is native to PSQL.
Second query syntax should be select * from table where value like any (array?1) as ?1 will be substituted by ['%foo%', '%bar%', '%baz%'], so your end query will match required PSQL syntax.
select * from table where value like any (array['%foo%', '%bar%', '%baz%'])
Firstly, your syntax is wrong.
Instead of:
select * from table where value like any (array[?1]);
You should use:
select * from table where value like any (:vals);
You cannot use array[?] or array[:var] to construct the variable. That is invalid syntax.
Secondly for Hibernate 5.2 up to 5.4 you can just add this dependency and you can use the most common object arrays directly. Primitive arrays are not supported and are not supposed to be.

Possibility of SQL query to return a result set that has more than one column with the same name

From oracle doc
http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/resultset.html
In some cases, it is possible for an SQL query to return a result set
that has more than one column with the same name. If a column name is
used as the parameter to a getXXX method, getXXX will return the value
of the first matching column name.
Anybody knows about "some cases"?
The simplest case is
select 1 as A, 2 as A from dual
much the same way someone may (unwillingly) create equal aliases in a complex query.
Imagine two tables defined as
Authors: AuthorId, FirstName, LastName, Title...
Books: BookId, Title, ISBN, AuthorId...
where one would want to list books with author information using the following SQL
SELECT *
FROM Books
JOIN Authors USING (AuthorId)
Now you have two unrelated title columns in the ResultSet, one being the title of the book and one being the (e.g. academic) title of the author.
Here's a common example:
SELECT * FROM table1 JOIN table2 ON table1.table1Id = table2.table1Id;
Here you know table1 and table2 have a column named table1Id, and it is guaranteed to have the same value. However if you have a self-join:
SELECT * FROM employee e JOIN employee m ON e.manager_id = m.id;
Now you have a problem and, probably, your result set will not make as much sense.

Issue with wildcards in Java prepared statements

I currently confused at how to set wildcards for long values when using select in databases. Currently I have:
preparedstatement= conn.prepareStatement("SELECT * FROM database WHERE LONGVALUES LIKE ? ");
preparedstatement.setLong(1, aLongValue);
I am currently confused on how to use a wild card to get the results that I want. What I want to select is all values from that database whose LONGVALUES column contains the number aLongValue. So if 52 is in the database entering 5 or 2 would select it.
You can't do LIKE on a numerical value. It must be a string so you should either make LONGVALUES a VARCHAR field or use a scalar function to convert the value to a string in line with your query i.e.
SELECT * FROM database WHERE TO_CHAR(LONGVALUES) LIKE ?;
To use LIKE, your aLongValue should be a varchar, then you can run a ... where longvalues like '%5%'

Error occurring in Hibernate when join column is String

I have two tables that I want to join using hibernate. The join column, as represented in my model is a String (its a varchar(10) in my database). When I run the HQL query, what I see is the following error, "conversion failed when converting the varchar value 'AS00' to data type int. "AS500" is the first value of join column in the first row.
I do not know why hibernate is doing this. My join column is not an int. I have checked both models corresponding to my tables and they are both defined as Strings. Is there some kind of restriction on the data types that can be used for join columns?
Please post both your model and the hql query.
If I had to take a guess (and that's all any of us can do without specifics), I would say that your hql query does not use .setParameter and it does not have single quotes around the string value in your query... so it is trying to implicitly convert the value to int.
Example that would cause this error:
Query query = session.createQuery("from Person where name = bob");

What does "Select Distinct Null As xxxxx" mean?

Background: I am mapping Sybase stored procedure return values to java objects using Spring.
For example I map a Sybase datatype of varchar as a String type in Java, and a Sybase datatype of int as an int type in Java, etc.
I have come across the following code in one of the stored procedures:
SELECT DISTINCT
A.Col1 AS val1,
A.Col2 AS val2,
NULL AS someVal,
A.col3 AS val3,
...
A.col9 AS val9
FROM #SomeTable A
ORDER BY Col2, Col3
I have 2 related questions:
What does Null mean in this scenario? I am confused as to what is happening here.
I am able to determine the data type of Col1, Col2, etc. of course by looking at the table definition of Table A defined earlier in the stored procedure. Thus I know what datatype I can define in my Java object for val1, val2, etc.. But what about "someVal"? What datatype mapping am I supposed to perform for this Null value?
I am fairly inexperienced in SQL. Perhaps the answer is much simpler than I realize.
This creates a column with NULL values in all rows. This trick is useful when
The reader of your query results expects a column someVal to be there, treating situations when this column is missing as errors, or
Your query is part of a UNION ALL query inside a GROUP BY query, with other queries filling in values for NULLs.
Here is an example of the later situation:
SELECT -- This query flattens the results of the two sub-queries
document_id
, MIN(approval_date) as approval_date
, MIN(availability_date) as availability_date
FROM (
SELECT -- This subquery supplies approval_date
document_id
, MAX(approval_date) AS approval_date
, NULL AS availability_date
FROM document_approvals
GROUP BY document_id
UNION ALL
SELECT -- This subquery supplies availability_date
document_id
, NULL AS approval_date
, MAX(availability_date) AS availability_date
FROM document_approvals
GROUP BY document_id
)
GROUP BY document_id
You will have a column called someVal with NULL as the value for each row.
With a ResultSet, you can use getString(int) or getString(String) which states
Returns: the column value; if the value is SQL NULL, the value
returned is null
You can choose any reference type you want, including Void, to map this column. Or don't use any, ie. don't map it. Depends on your requirement.

Categories