This question already has answers here:
SQL query: Can't order by column called "order"?
(7 answers)
Closed 3 years ago.
i want to show the list of orders through api but we have an error in the DAO SQLSyntaxErrorException.
#RequestMapping("list")
public String getAllOrders() {
//APIResponse response=new APIResponse();
List<OrderBeans> orderList = orderDao.selectAll();
return new Gson().toJson(orderList);
}
public List<OrderBeans> selectAll() {
System.out.println("DAO => " + jdbcTemplate);
List<OrderBeans> orders = null;
String query = "select * from " + TABLE_ORDER +"";
try {
orders = jdbcTemplate.query(query, new OrderRowMapper());
} catch (EmptyResultDataAccessException | IncorrectResultSetColumnCountException e) {
}
return orders;
}
3-May-2019 15:01:15.997 SEVERE [http-nio-8084-exec-109] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/Grocery] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [select * from order]; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1] with root cause
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order' at line 1
I am speculating here that your error is due to your SQL table being called ORDER, which of course is a reserved keyword in almost all versions of SQL. You should always avoid naming your tables and columns with reserved keywords. As a workaround, you could build your query as follows, placing backticks around the table name:
String query = "select * from `" + TABLE_ORDER + "`";
However, the above should only be viewed as a temporary solution until you get a chance to fix your data model.
Related
I am developing a full text search service. I use PostgreSQL's built-in FTS query syntax. As you know, I need to use ## characters to use it. But, this characters are not recognized by HQL, you cannot directly write it like inside the sql. One option is to use nativeQuery, which I used to use. But, due to software's requirements, now I need to use HQL. For this purpose, I tried to implement this implementation.
In that implementation first you create a PostgreSQLFTSFunction class. For me it is:
public class BFTSFunction implements SQLFunction {
#Override
public boolean hasArguments() {
return true;
}
#Override
public boolean hasParenthesesIfNoArguments() {
return false;
}
#Override
public Type getReturnType(Type type, Mapping mapping) throws QueryException {
return new BooleanType();
}
#Override
public String render(Type type, List list, SessionFactoryImplementor sessionFactoryImplementor)
throws QueryException {
if (list.size() != 2) {
throw new IllegalArgumentException("The function must be passed 3 args");
}
String field = (String) list.get(0);
String value = (String) list.get(1);
String fragment = null;
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery('%" +
value + "%')) ";
return fragment;
}
}
Then need to create CustomPostgreSQLDialect:(I have, for sure, added dialect configuration onto application.yml file)
public class FTSPostgresDialect extends PostgisDialect {
public FTSPostgresDialect() {
super();
registerFunction("fts", new BFTSFunction());
}
}
Lastly I created HQL in my RepositoryImp
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,:searched) = true )",Long.class).setParameter("searched",searched);
List<Long> listResults = q.getResultList();
But the query created by hibernate cannot be executed. Full error will be given below, but I should say that, logged query in the console (created by Hibernate) can be executed in pgAdmin. Therefore, Query creation process is correct. Then, where can be the error is?
Full error is given:
rg.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [select b0_.id as col_0_0_ from bs b0_ where ( b0_.deleted=false) and ( to_tsvector(coalesce(b0_.name,' ')) ## plainto_tsquery('%?%')) =true]; nested exception is org.hibernate.exception.DataException: could not execute query
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
...
Caused by: org.hibernate.exception.DataException: could not execute query
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:118) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
...
Caused by: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128) ~[postgresql-42.2.5.jar:42.2.5]
2019-07-16 10:08:59.328 ERROR 8248 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [select b0_.id as col_0_0_ from bs b0_ where ( b0_.deleted=false) and ( to_tsvector(coalesce(b0_.name,' ')) ## plainto_tsquery('%?%')) =true]; nested exception is org.hibernate.exception.DataException: could not execute query] with root cause
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:996) ~[postgresql-42.2.5.jar:42.2.5]
If additional info is needed, I will fastly send it. Thanks in advance.
Interestingly, as the error suggests, hibernate cannot bind the parameters onto sql. I couldn't make it happen. But in my situation, I could just concatenate as string, therefore problem is resolved by changing HQL from:
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,:searched) = true )",Long.class)
.setParameter("searched",searched);
to:
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,"+searched+") = true )",Long.class);
The problem is unnecessary quotes in a plainto_tsquery call:
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery('%" +
value + "%')) ";
It should be:
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery(" +
value + ")) ";
I removed those % too, because it won't work like that. value won't have an actual parameter value, it would have ? in it to create a query, that will be reused for actual executions. If you want to wrap the given value into %, you'll have to do it with SQL, not Java code.
I am using JDBCTemplate to query a SQL server using:
List results = jdbc.query(statement, new ResultDataMapper());
I have tried the statement in PreparedStatementCreator and String formats but neither work. I received the exception below:
SQL state [null]; error code [0]; The statement did not return a result set.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
My sql is:
IF OBJECT_ID('tempdb.dbo.#tempSearch', 'U') IS NOT NULL
DROP TABLE #tempSearch;
CREATE TABLE #tempSearch
(
ID int,
Value VARCHAR(255)
)
INSERT INTO #tempSearch
VALUES(1,'?'),
(2,'?');
with cte as (
select RoleID,','+replace(replace(GroupNames,',',',,'),' ','')+',' GroupNames from UserGroup_Role_Mapping
)
,cte2 as(
select cte.RoleID, replace(cte.GroupNames,','+Value+',','') as GroupNames, s.ID, s.Value
from cte
join #tempSearch s on ID=1
union all
select cte2.RoleID, replace(cte2.GroupNames,','+s.Value+',','') as l, s.ID ,s.Value
from cte2
join #tempSearch s on s.ID=cte2.ID+1
)
SELECT a.Role, a.Sort_Order, a.Parent, a.Parent_ID, a.Parent_URL, a.Child, a.Child_ID,a.Child_URL
FROM NC_View a
WHERE a.Role IN (
Select Name from (
Select distinct RoleID from cte2 where len(GroupNames)=0
) tempRoles
join User_Role
on tempRoles.RoleID = User_Role.ID
)
DROP TABLE #tempSearch
I know the SQL works fine but i just cant get over the hump of calling it from JDBC. I have the Mapper and extractor all done too.
I ran this with a PreparedStatementCreator and String:
when i use PreparedstatementCreator and try to set 2 variables I get index out range errors "com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.":
PreparedStatementCreator returnValue = new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
sql.append("("+x +",'" + "?" +"'),"); //when constructing the sql
PreparedStatement statement = con.prepareStatement(sql.toString());
statement.setString(z++, group); //when setting those values
I am not sure why this is? is the syntax incorrect? It seems it is not detecting the set?
from debug i also see:
Unable to translate SQLException with Error code '0'
If I use String straight out i get:
org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQLException for SQL [
SQL FROM ABOVE - I TESTED AND IT WORKS
]; SQL state [null]; error code [0]; The statement did not return a result set.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
I am not sure if the SQL is too complex or what. But also confused how using PreparedStatementCreator it wasnt detecting the ? to set variables... I am running out of ideas. I tried Multiqueries=true too
If I use SET NOCOUNT ON i get a different error:
Unable to solve uncategorized SQLException when calling SQL Server using JDBC
So i am bit confused too. I am not inserting a lot of data so maybe it doesn't matter?
Thanks!
I am developing a Java Restful Web Application. When I try to execute this SQL Query using JDBCTemplate it gives and error saying that,
SEVERE: Servlet.service() for servlet [spring-mvc] in context with path [/paf_project] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select count(*) from customer where email = ? AND password = ? AND status = ?]; nested exception is java.sql.SQLException: No value specified for parameter 3] with root cause
java.sql.SQLException: No value specified for parameter 3
Here is my Function which I am going to get the row count of my table.
public int userLogin(String un, String pw) {
String status = "active";
String sql = "select count(*) from customer where email = ? AND password = ? AND status = ?";
int count = template.queryForObject(sql, new Object[] {un, pw, status}, Integer.class);
if(count >= 1) {
return 1;
}
I have an SQL query that is executed using Spring JDBCTemplate to retrieve data from an Oracle DB. While executing the statement, org.springframework.jdbc.BadSqlGrammarException is thrown.
The same SQL statement returns proper results when run in the SQL Plus console.
Below is the code that I am trying to execute:
String query = "SELECT DISTINCT O.ORGID FROM ORGANISATIONS O WHERE O.ORGTYPE NOT IN ('P','G') AND O.USERID = 40";
ArrayList<Organisations> orgsList = new ArrayList<Organisations>();
Object[] paramsArray = new Object[]{};
orgsList = (ArrayList<Organisations>) getJdbcTemplate().query(query.toString(), paramsArray ,
new RowMapper<Organisations>(){
public MetricsRoleMap mapRow(ResultSet rs, int rowNum) throws SQLException {
// Data retrieval code;
};
});
Here is the error generated:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [ SELECT DISTINCT O.ORGID FROM ORGANISATIONS O WHERE O.ORGTYPE NOT IN ('P','G') AND O.USERID = 40]; nested exception is java.sql.SQLException: Invalid column name
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:660) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:695) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:727) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:737) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:787) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
Similar code that I wrote for another method works well. I think there is a minor mistake here, but I am unable to find it.
I am trying to retrieve data from my database with hibernate but it keeps throwing an exception
2012-11-11 11:35:45,943 [main] ERROR
com.storage.hibernate.DatabaseAccessRequestsImpl - there was an error
javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not execute query
#Override
public List<Trade> requestPeriod() {
List<Trade> trades = null;
EntityManager manager = emf.createEntityManager();
Query query = manager.createQuery("from trade");
try{
trades = query.getResultList();
}
catch(PersistenceException e){
logger.error("there was an error " + e);
}
catch(SQLGrammarException e){
logger.error("there was an error " + e);
}
return trades;
}
I am guessing the syntax I am using for select all is incorrect but after looking around I can not see an alternative?
Thanks
It should be "from Trade" (uppercase T) as Trade is the name of the mapped class.
Note that in JPA QL SELECT clause is mandatory, as per: 10.2.1.1. JPQL Select Statement:
A select statement is a string which consists of the following clauses:
a SELECT clause, which determines the type of the objects or values to be selected;
a FROM clause, which provides declarations that designate the domain to which the expressions specified in the other clauses of the query apply;
[...]
In BNF syntax, a select statement is defined as:
select_statement ::= select_clause from_clause [where_clause] [groupby_clause] [having_clause] [orderby_clause]
The bare from Trade syntax is Hibernate-specific, to be specification compliant you should always use:
select t from Trade t