Pass Integer Array for Number column in database - java

I have query looks like SELECT * from TableName WHERE id= ?
for id field I want to pass array of ids which Number field in Database,
I have created Number Array type i database, when I pass Array to my prepared statement I get following error.
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * from Tablename WHERE id= ?]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected NUMBER got schema.app_id
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:95)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springfra

You need to use a table collection expression in your query:
The table_collection_expression lets you inform Oracle that the value of collection_expression should be treated as a table for purposes of query and DML operations. The collection_expression can be a subquery, a column, a function, or a collection constructor. Regardless of its form, it must return a collection value—that is, a value whose type is nested table or varray. This process of extracting the elements of a collection is called collection unnesting.
So you need to convert your passed collection (array) to a table in a subquery within your in() clause:
SELECT * from TableName WHERE in (SELECT column_value FROM TABLE(?))
Or with a join:
SELECT t.*
FROM TABLE(?) i
JOIN TableName t
ON t.id = i.column_value

Related

Error while executing HQL with group by clause

I am using the following HQL query:
List<Object> object = session.createQuery("select userId, count(*) from Tweet " +
"group by userId", Object.class).getResultList();
It's causing the following error:
Caused by: org.hibernate.query.QueryTypeMismatchException: Query
result-type error - multiple selections: use Tuple or array at
org.hibernate.query.sqm.internal.QuerySqmImpl.checkQueryReturnType(QuerySqmImpl.java:367)
at
org.hibernate.query.sqm.internal.QuerySqmImpl.visitQueryReturnType(QuerySqmImpl.java:328)
at
org.hibernate.query.sqm.internal.QuerySqmImpl.(QuerySqmImpl.java:227)
at org.hibernate.internal.AbstractShare
what could be the reason for this?
Is it because I am selecting specific columns in it?
Your select clause is returning two things, therefore the type signature of the method should be List<Object[]>. Use this version:
List<Object[]> object = session.createQuery("select userId, count(*) from Tweet " +
"group by userId", Object[].class).getResultList();
But note that you could also define an entity which matches the select clause. Then, you could avoid the cumbersome Object[] result set type.

Setting a collection parameter as a list for column values

I'm trying to write a query with a Collection parameter. It is assumed that query would turn this collection to a column of its values for the further operations. I'm using Spring, so now my query looks like:
#Query(value = "SELECT id FROM unnest(array[?1]) id", nativeQuery = true)
List<Object> getIds(Collection<String> ids);
It doesn't work, because Hibernate set collections as parameters in braces, so the real query will be send to DB:
SELECT id FROM unnest(array[('1', '2')]) id
This is not a valid query, the error is raising:
ERROR: a column definition list is required for functions returning
"record" SQL state: 42601
Right version of it must be:
SELECT id FROM unnest(array['1', '2']) id
So please can anybody tell me, if there is a way I could set a collection as query parameter without braces? Or maybe there is an another way to turn collection to column?

How to order by a specific column a MySQL query with Java and Hibernate?

I'm trying to use the same query to sort my table columns but when I pass as a parameter the column to ORDER BY, it adds quotes before and after my column name. If you are using ORDER BY parameter, the column name have to be written without being between quotes or MySQL is going to ignore it.
Example or query to execute:
select * from app_user ORDER BY mobile_token ASC LIMIT 0 , 20
This is what hibernate send to MySQL:
select * from app_user ORDER BY 'mobile_token' ASC LIMIT 0 , 20
Java query:
query = JPA.em().createNativeQuery("select * from app_user ORDER BY :column ASC LIMIT :init , :page",AppUser.class);
query.setParameter("column", column);
query.setParameter("init", pageNumber*pageSize);
query.setParameter("page", pageSize);
I could change the NativeQuery by:
"select * from app_user ORDER BY "+column+" ASC LIMIT :init , :page"
but this is going to become my app unsafety.
You can only pass values as parameters to a query. Not column or field names. That would make it impossible for the database to know which columns are actually used in the query, and thus make it impossible to prepare the execution plan.
So your solution using concatenation is the only one. Just make sure the column doesn't come from the user. Or if it comes from the user, that it's a valid column name and that the user is allowed to use it.

How to compare Integer type record with String Type Record in MS_Access?

I have two tables in my DB.
Table Other Has RMA_no as 'Number'
& table Material_Require_Master Has RMA_No as TEXT.
I want to perform a query that can output tuples that have matching RMA_No?
So far I have done this.
String sql="Select RMA_Master.RMA_No,Call_Date,Source,Item_name,
Booking_Desc,Customer_name,Customer_contact,
AssignedTo,Part_No,Part_Name,Part_Quantity,
Part_Price,Total
From RMA_Master,Material_Require_Master
WHERE RMA_Master.RMA_No=Material_Require_Master.RMA_No AND
RMA_Master.MaterialRequireStatus='"+materialStatus+"'
UNION
Select Other.RMA_No,Call_Date,Source,Item_name,
Booking_Desc,Customer_name,Customer_contact,
AssignedTo,Part_No,Part_Name,Part_Quantity,
Part_Price,Total
From Other,Material_Require_Master
WHERE String.valueOf(Other.RMA_No)= Material_Require_Master.RMA_No AND
Other.MaterialRequireStatus='"+materialStatus+"'";
PreparedStatement pst=con.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
pst.close();
And my StackTrace is :
Exception: [Microsoft][ODBC Microsoft Access Driver] Undefined function 'String.valueOf' in expression.
Also When I don't use String.valueOf:
String sql="Select RMA_Master.RMA_No,Call_Date,Source,Item_name,Booking_Desc,Customer_name,Customer_contact,AssignedTo,Part_No,Part_Name,Part_Quantity,Part_Price,Total From RMA_Master,Material_Require_Master WHERE RMA_Master.RMA_No=Material_Require_Master.RMA_No AND RMA_Master.MaterialRequireStatus='"+materialStatus+"' UNION Select Other.RMA_No,Call_Date,Source,Item_name,Booking_Desc,Customer_name,Customer_contact,AssignedTo,Part_No,Part_Name,Part_Quantity,Part_Price,Total From Other,Material_Require_Master WHERE Other.RMA_No= Material_Require_Master.RMA_No AND Other.MaterialRequireStatus='"+materialStatus+"'";
Following Exception occurs:
Exception: [Microsoft][ODBC Microsoft Access Driver] Type mismatch in expression.
I think you messed up between SQL and Java.
String.valueOf() is a Java method you can't use in your SQL statement. There is STR() in SQL that you can use to convert a number into a string. Use it in conjonction with LTRIM() in order to remove whitespace padding, e.g. LTRIM(STR(Other.RMA_no)).
But anyway, the other way around is better as proposed by #Gord.
With two test tables
[Material_Require_Master]
RMA_No - Text
mrmText - Text
[Other]
RMA_no - Number (Long Integer)
otherText - Text
The following query ...
SELECT Other.RMA_no, Other.otherText, Material_Require_Master.mrmText
FROM Material_Require_Master INNER JOIN Other
ON Material_Require_Master.RMA_No = Other.RMA_no;
... does indeed produce the error
Type mismatch in expression.
If we add the CLng() function to the ON clause of the join to convert Material_Require_Master.RMA_No from text to a long integer ...
SELECT Other.RMA_no, Other.otherText, Material_Require_Master.mrmText
FROM Material_Require_Master INNER JOIN Other
ON CLng(Material_Require_Master.RMA_No) = Other.RMA_no;
... then the query runs without error.

SQL to Hibernate Query Language (HQL) - missing IN

Desired SQL statement to convert
select * from tableA where columnA is not null
order by cast(columnA as int), columnB
union all
select * from app_data_program where columnA is null order by columnB
My HQL attempt:
From TableA a where a.columnA is not null
order by cast(a.columnA as int), a.columnB
union all TableA b where b.columnA is not null order by b.columnB
When I converted the HQL to SQL to test as a result, i get the following:
SQL Error: Missing IN or OUT parameter at index:: 1
HQL doesn't allow use UNION ALL sql construct.
You must execute two different queries and then you can merge the results of them.
So you'll have:
First query:
From TableA a where a.columnA is not null
order by cast(a.columnA as int), a.columnB
Second query:
TableA b where b.columnA is not null order by b.columnB

Categories