when i run below query in my springboot project
select * from activity.activity where data->'userinfo' #> '[{"name": :username}]'::jsonb
i get this error "Could not locate named parameter [username], expecting one of []".
The table has a data column with value as {"userinfo": [{"name": "john"},{"lastname":"cena"}]}
What could be the issue?
PS: i am executing the query using the entity manager to create a native query, and then calling query.getResultList().
CODE:
StringBuffer q = new StringBuffer("select * from activity.activity where data->'userinfo' #> '[{\"name\":").append(" :username").append("}]'::jsonb");
Query query = null;
query = em.createNativeQuery(q.toString(), Activity.class);
query.setParameter("username", getActivityDataRequest.getUserName());
return query.getResultList();
That is a string literal. It cannot contain a parameter. You do have a :jsonb parameter, though. You should use ANSI SQL casting to avoid that.
Instead you should change your query to
String sql = "select * from activity.activity where data->'userinfo' #> CAST(:uname as jsonb)"
// next line is psudocode
String value = JsonBuilder.newArray( JsonBuilder.newObject("name", username) ).toString();
// real code
return em.createNativeQuery(sql, ResultClass.class)
.setParameter("uname", value)
.getResultList();
Related
Below is my query to filter the json column in MySQL table ,
public interface MpaCustomizationRepository extends
JpaRepository<MpaCustomization, Serializable> {
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, '{\"id\" : ?1}')")
MpaCustomization findByDomainBaseId(String domainId);
}
above method throws below SQL error,
but if I hard code the variable and run the query like below its works fine,
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, '{\"id\" : 2}')")
MpaCustomization findByDomainBaseId(String domainId);
How to fix this issue?
Use $.id for values when using native query, as SQL accepts like it only.
Other way, you may use :id and bind parameter {\"id\":\"" + <value> + "\"} to the query.
Maybe the following will work.
#Query(nativeQuery = true, value = "select * from MPA_CUSTOMIZATION where json_contains(domain_based_properties, ?1 , '$.id'")
MpaCustomization findByDomainBaseId(String domainId);
Source
I am trying to a SQL query in Spring MVC 4 with order by clause. But it does not work. I am using MapSQLParameterSource class to define sql parameters.
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("lowerLimit", lowerLimit);
params.addValue("upperLimit", upperLimit);
params.addValue("filter", filter.trim()+"%");
params.addValue("order", order);
String sql = "SELECT * FROM tbl_Subject WHERE subjectName LIKE :filter ORDER BY :order limit :lowerLimit, :upperLimit";
It does not work actually. does not order any columns. When I try to hard coded it works fine as aspect.
String sql = "SELECT * FROM tbl_Subject WHERE subjectName LIKE :filter ORDER BY subjectId DESC limit :lowerLimit, :upperLimit";
How to I Order by clause query with MapSqlParameterSource.
The problem is in this line :
params.addValue("order", order);//consider this return col_name
This will be translate it to :
.. ORDER BY 'col_name' limit ..
^ ^
and this is a wrong syntax, logically after ORDER BY you have to pass a column name and not a value.
.. ORDER BY col_name limit ..
^^^^^^^^
Instead you have to pass it to the query directly but be carfull to pass the correct name, this can cause Syntax error or SQL Injection if you pass a wrong input
I have a problem with this query when I pass it to an oracle dbms
SELECT * FROM RD_RBF WHERE REQUEST_ID = 'S2N-F01-000000000001'
because of the dashes in the string the jvm return me this exception
java.sql.SQLException: Fail to convert to internal representation
How can I pass this query to oracle correctly? Thanks a lot
P.S. I'm not shure of the code because I'm using Talend software that generates automatically the code of components but I can post part of the code above
String dbquery_tOracleInput_1 = "SELECT * FROM RD_RBF WHERE REQUEST_ID = 'S2N-F01-000000000001'";
java.sql.ResultSet rs_tOracleInput_1 = null;
try{
rs_tOracleInput_1 = stmt_tOracleInput_1.executeQuery(dbquery_tOracleInput_1);
java.sql.ResultSetMetaData rsmd_tOracleInput_1 = rs_tOracleInput_1.getMetaData();
int colQtyInRs_tOracleInput_1 = rsmd_tOracleInput_1.getColumnCount();
Use toraclerow component.
Query as follows in component:
"SELECT * FROM RD_RBF WHERE REQUEST_ID = ?"
Go to advance setting, select use prepared statement and add 1 paarmeter index.
also select the propagate Query's record set.
tOracleRow_1 -----> tParseRecordSet----->
when i run my query in database visualizer its working perfectly, but i think there are some issues in syntax when i convert it in my DAO class method.
I want to get whole data against the name provided
In Visualizer:
SELECT first_name,last_name,nic,phone,email FROM x_hr_user where (first_name = 'Irum');
Now in Dao
public List<XHrUser> findXHrUserByNameInTable()
{
String name ="Irum";
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = (name)");
List<XHrUser> list = query.getResultList();
return list;
}
Instead of showing single row, it displays whole data Table
Thank you
Your current query is not valid JPQL. It appears that you intended to insert the raw name string into your query, which could be done via a native query, but certainly is not desirable. Instead, use a named parameter in your JPQL query and then bind name to it.
String name = "Irum";
Query query = em.createQuery("SELECT x FROM XHrUser WHERE x.firstName = :name")
.setParameter("name", name);
List<XhrUser> list = query.getResultList();
You have to write query as below. where : is used for variable
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = :name");
I have this piece of code, with a prepared statement. I know the query is redundant. the parameter id is a string <space>413530 (" 413530"). Please note the preceding whitespace character.
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=?";
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
newPrepStatement.setString(1, id);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I do not get any results after executing this query.
Now, if I use the same statements and append the parameter as part of the string as follows:
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=" + id;
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I get a result as after executing this prepared statement. Same also works with a java.sql.statement
I wish to know why the driver ignores the whitespace in the second piece of code, but has a problem in the first part.
If you use setString the parameter will be bound as a string resulting in this SQL (considering the bound parameter an SQL string):
SELECT RSCode as id FROM Customer WHERE RSCode=' 0123';
If you use concatenation the SQL used will be (considering the concatenated value as an integer, since space will be ignored as part of the SQL syntax):
SELECT RSCode as id FROM Customer WHERE RSCode=<space>0123;
In this case I would advise to convert it to int or long or whatever it is and bind it with the right type. With setInt() or setLong().
And if you field is a string you could normalize it first using for example:
String normalizedValue = String.trim(value);
newPrepStatement.setString(1, normalizedValue);
or even direct in SQL like:
SELECT RSCode as id FROM Customer WHERE RSCode=TRIM(?);
In scenario - 1, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode=' 413530'"
In scenario - 2, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode= 413530"