How to remake this code to work with oracle. Before that, it worked with Postgres and there were no errors. Now it gives sql grammatical error.
public List<MyOrder> myOrderListNew(Company company){
Criteria criteria = session.getCurrentSession().createCriteria(MyOrder.class);
criteria.add(Restrictions.eq("company.id", company.getId()));
criteria.add(Restrictions.eq("removeorder", false));
criteria.add(Restrictions.eq("status", "new"));
criteria.addOrder(Order.desc("id"));
List<MyOrder> myOrders = criteria.list();
return myOrders;
}
about the : criteria.add (Restrictions.eq ("company.id", company.getId ()));
"company.id", here company this property in the entity class MyOrder.
StackTrace
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:69)
java.sql.SQLSyntaxErrorException: ORA-01747: invalid user.table.column, table.column, or column specification
oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494)
oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446)
oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054)
oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623)
oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
Error : 1747, Position : 144, Sql = select this_.myOrder_id as myOrder_id1_6_0_, this_.myorder_company_id as myorder_company_id9_6_0_, this_.courier_id as courier_id10_6_0_, this_.date as date2_6_0_, this_.date_hms as date_hms3_6_0_, this_.hide as hide4_6_0_, this_.removeorder as removeorder5_6_0_, this_.selected as selected6_6_0_, this_.shops_id as shops_id11_6_0_, this_.status as status7_6_0_, this_.sum as sum8_6_0_ from myorder this_ where this_.myorder_company_id=:1 and this_.removeorder=:2 and this_.status=:3 order by this_.myOrder_id desc, OriginalSql = select this_.myOrder_id as myOrder_id1_6_0_, this_.myorder_company_id as myorder_company_id9_6_0_, this_.courier_id as courier_id10_6_0_, this_.date as date2_6_0_, this_.date_hms as date_hms3_6_0_, this_.hide as hide4_6_0_, this_.removeorder as removeorder5_6_0_, this_.selected as selected6_6_0_, this_.shops_id as shops_id11_6_0_, this_.status as status7_6_0_, this_.sum as sum8_6_0_ from myorder this_ where this_.myorder_company_id=? and this_.removeorder=? and this_.status=? order by this_.myOrder_id desc, Error Msg = ORA-01747: invalid user.table.column, table.column, or column specification
oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498)
oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446)
oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054)
oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623)
oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
Formatted, query you use is this. I've marked what seems to be wrong: column names can't be DATE nor SUM as these are reserved words (for a datatype and a function).
SELECT this_.myOrder_id AS myOrder_id1_6_0_,
this_.myorder_company_id AS myorder_company_id9_6_0_,
this_.courier_id AS courier_id10_6_0_,
this_.date AS date2_6_0_, --> this
this_.date_hms AS date_hms3_6_0_,
this_.hide AS hide4_6_0_,
this_.removeorder AS removeorder5_6_0_,
this_.selected AS selected6_6_0_,
this_.shops_id AS shops_id11_6_0_,
this_.status AS status7_6_0_,
this_.SUM AS sum8_6_0_ --> this
FROM myorder this_
WHERE this_.myorder_company_id = :1
AND this_.removeorder = :2
AND this_.status = :3
ORDER BY this_.myOrder_id DESC
What to do? Depends on table description. If you managed to create such a table, then you must have enclosed column names into double quotes. If that's so, you'll have to do the same every time you work with those columns, e.g.
SQL> create table myorder
2 ("DATE" date,
3 "SUM" number
4 );
Table created.
SQL> -- this is what you are currently doing; see? The same ORA-01747 error
SQL> select this_.date,
2 this_.sum
3 from myorder this_;
select this_.date,
*
ERROR at line 1:
ORA-01747: invalid user.table.column, table.column, or column specification
SQL> -- this is what you should be doing
SQL> select this_."DATE",
2 this_."SUM"
3 from myorder this_;
no rows selected
SQL>
If possible, change column names to make your life easier.
Related
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1617)
Util.SQLControl.insertOrderLine(SQLControl.java:66)
Servlet.ShoppingCardServlet.processRequest(ShoppingCardServlet.java:53)
Servlet.ShoppingCardServlet.doPost(ShoppingCardServlet.java:81)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause:
org.hibernate.exception.SQLGrammarException: could not execute statement
org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:107)
org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1632)
org.hibernate.query.internal.NativeQueryImpl.doExecuteUpdate(NativeQueryImpl.java:295)
org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608)
Util.SQLControl.insertOrderLine(SQLControl.java:66)
Servlet.ShoppingCardServlet.processRequest(ShoppingCardServlet.java:53)
Servlet.ShoppingCardServlet.doPost(ShoppingCardServlet.java:81)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'pepsi' in 'field list'
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
com.mysql.jdbc.Util.getInstance(Util.java:381)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:107)
org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1632)
org.hibernate.query.internal.NativeQueryImpl.doExecuteUpdate(NativeQueryImpl.java:295)
org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1608)
Util.SQLControl.insertOrderLine(SQLControl.java:66)
Servlet.ShoppingCardServlet.processRequest(ShoppingCardServlet.java:53)
Servlet.ShoppingCardServlet.doPost(ShoppingCardServlet.java:81)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
public void insertOrderLine(String orderName, String tableId, String pID, String pName , String category, int quantity, int price, String date){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createSQLQuery("INSERT INTO "+ orderName+" VALUES ("+tableId +","+ pID+" ,"+pName +
","+category+","+quantity+ ","+ price+" ,"+ date+")");
int result = query.executeUpdate();
}
You dont seem to be setting the columns to insert your values into! when you execute an insert query you need to specify exactly which columns to insert into, like so
INSERT INTO table([column1], [column1]) VALUES(value_for_col1, value_for_col2).
Im guessing thatws why hibernate is complaining about unknown columns. just guessing from your input parameters i imagine your query will need to look like this:
Query query = session.createSQLQuery("INSERT INTO "+ orderName+" ([orderName], [tableId], [pID], [pName], [category], [quantity], [price], [date])VALUES ("+tableId +","+ pID+" ,"+pName +
","+category+","+quantity+ ","+ price+" ,"+ date+")");
Also for complex queries i suggest storing them within a sql file, this just makes editing easier and makes the code a bit neater. then just load the sql file as a string.
An even easier method to save in hibernate would just be to create an entity object, (create a class then annotate with #Entity). Hibernate will then save this object for you avoiding the need for native update queries!
This question already has answers here:
Multiple queries executed in java in single statement
(6 answers)
Closed 4 years ago.
String query = "INSERT INTO St (id) values ('Admin'); " +
"select * from Student where id in (select id from St);";
Getting error if try to execute the above query
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:226)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:59)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:910)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3780)
at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1343)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3822)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1165)
at com.prototype.service.DBConnection.main(DBConnection.java:167)
Caused by: Error : 933, Position : 36, Sql = INSERT INTO St (id)
values ('Admin'); select * from Student where id in (select id from
St);, OriginalSql = INSERT INTO St (id) values ('Admin'); select *
from Student where id in (select id from St);, Error Msg = ORA-00933:
SQL command not properly ended
you can use a insert select statement and this way avoid multi statemenst query
String query = "INSERT INTO St (id)
select your_col_for_id from Student where id in (select id from St);";
and you must be sure you have corresponding number and type of column in into clause and in select clause
Still new to hibernate custom queries.
My table is
ID TID R1 Position
1 1 1 2
2 1 1 3
I want a custom query to delete rows with TID 1 and R1 1
My current sql looks like
#Query(value = "delete from Table t where t.TID= :tid and t.R1 = :r1", nativeQuery = true)
void deleteByTIDAndR1(#Param("tid") Integer TID, #Param("r1") Integer r1);
It gives me the following error:
.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
My controller retrieves the right tid and r1 ID's.
Is it even possible to delete multiple rows at once? And where could my error be?
Edit
After I add #Modyfying to the query i get the error
TransactionRequiredException: Executing an update/delete query
And after i add #Transactional in combination with #Modifying i get
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 't where t.tid= 1 and t.R1 = 99' at line 1
I think you lack the #Modifying annotation, indicating a query that modify the database:
#Modifying
#Query(value = "delete from Table where TID= :tid and R1 = :r1", nativeQuery = true)
void deleteByTIDAndR1(#Param("tid") Integer TID, #Param("r1") Integer r1);
And yes this method can delete zero, one or more rows.
i am trying to fetch the id of last column in descending order.
the query which returns last column is
select id from(select id from challan
order by id desc) where ROWNUM=1;
now i am trying to do same thing using hibernate.
public long getIdOnChallanTable() {
session = sessionFactory.openSession();
trans = session.beginTransaction();
Query<Object[]> query = session.createNativeQuery("select id
from(select id from challan order by id desc) where ROWNUM=1;");
Long value = 0L;
List<Object[]> list = query.getResultList();
for ( Object lst : list){
Object[] objects =(Object[]) lst;
value=(Long)(objects[0]);
}
return value;
}
and the error is:
2017-07-26 12:37:36 [http-nio-7080-exec-1] WARN :: SQL Error: 911, SQLState: 22019
2017-07-26 12:37:36 [http-nio-7080-exec-1] ERROR:: ORA-00911: invalid character
update error javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
You don't need the semicolon at the end of the query and please use proper whitespacing. In the FROM clause, you don't have the whitespace between the subquery and the FROM keyword.
Note: don't forget to commit/rollback the transaction at the end and handle the exceptions as well. I hope this was just a sketch to show us the problem and not a code from a real world application.
We are trying to create hibernate specific query for below
lSession.createQuery(lQueryString.toString());
............
INSERT INTO EMPLOYEE_HISTORY (emp_status,
createdBy,
releasedate,
year)
SELECT CASE n.emp_Status WHEN 0 THEN 'Draft' ELSE 'Final' END,
m.createdBy,
m.releasedate,
m.year
FROM EMPLOYEE m, (SELECT COUNT (1) EMPLOYEE_HISTORY b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n
where a.doc_id='xyz'
getting following exception,I guess it because of below statement in query
(SELECT COUNT (1) EMPLOYEE_HISTORY b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 374
INSERT INTO EMPLOYEE_HISTORY (emp_status,
createdBy,
releasedate,
year)
SELECT CASE n.emp_Status WHEN 0 THEN 'Draft' ELSE 'Final' END,
m.createdBy,
m.releasedate,
m.year
FROM EMPLOYEE m, (SELECT COUNT (1) EMPLOYEE_HISTORY b,EMPLOYEE a where a.emplid=b.emplid and a.year=b.year and b.year=2012 and a.doc_id='XYZ') n
where a.doc_id='xyz'
The Exception
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
Please provide if any suggestion/Inputs.
It looks, like you pass SQL instead of HQL to the Session.createQuery(...) method.
See: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-querying-executing
For example in:
INSERT INTO EMPLOYEE_HISTORY (...)
'EMPLOYEE_HISTORY' should be entity class name (like EmployeeHistory) not the table name.
Also in HQL you can use references defined in your entities to go through associations avoiding implicit joining by ids, like you do here
where a.emplid=b.emplid and ...
Consider example from URL above:
select mother from Cat as cat join cat.mother as mother where cat.name = ?