Hibernate SQLSyntaxErrorException - SQL Error: 1064, SQLState: 42000 - java

Good morning, I'm dwelling with this error on a DAOImpl method from this morning... it happened all of a sudden..
This is my method:
public int postiOccupatiParcheggio(Park park) {
Query pianiQuery = getSession().createQuery("from Piano p where p.park = :park");
pianiQuery.setParameter("park", park);
List <Piano> piani = pianiQuery.list();
Query postiQuery = getSession().createQuery("from Posto p where p.piano in :piani");
postiQuery.setParameterList("piani", piani);
List<Posto> posti = postiQuery.list();
Query query = getSession().createQuery("SELECT count(*) from Occupazione o where o.posto in :posti "
+ "and o.occupied = true and o.dateTime = (select max(oo.dateTime) from "
+ "Occupazione oo where o.posto = oo.posto)");
query.setParameterList("posti", posti);
Long r = null;
int result = 0;
try {
r = (Long) query.uniqueResult();
result = r.intValue();
} catch(NoResultException nre) {
result = 0;
}
return result;
}
I'm getting this exception
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 ')) and occupazion0_.isOccupied=1 and
occupazion0_.date_time=(select max(occupazi' at line 1
and hibernate logs tells:
SQL Error: 1064, SQLState: 42000
I read that this is an error that occurs if you use some restricted variables names, but it's not the case, and most of all, everything went good till yesterday...
I'm using MySql 5.7.9 and with this property:
hibernate.dialect = org.hibernate.dialect.MySQLDialect

Related

java.sql.SQLSyntaxErrorException when using SQL variables in a query

This is my SQL query:
INSERT INTO SomeTable (UniqueID, SomeData, SomeNumber)
VALUES (#unique_id + 1, 'some value', '4234435435')
ON DUPLICATE KEY UPDATE
OtherNum = OtherNum + 1, SomeNumber = '999';
SELECT #unique_id := MAX(UniqueID) FROM SomeTable;
I use MariaDB. And I use HeidiSQL to manage databases, execute queries etc. In HeidiSQL my query works fine, but when I try to execute it in Java I get SQLSyntaxErrorException. Here is how I do it:
Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/somedb?user=root&password=password");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("INSERT INTO SomeTable (UniqueID, SomeData, SomeNumber)\n"
+ "VALUES (#unique_id + 1, 'some value', '4234435435')\n"
+ "ON DUPLICATE KEY UPDATE\n"
+ "OtherNum = OtherNum + 1, SomeNumber = '999';\n"
+ "SELECT #unique_id := MAX(UniqueID) FROM SomeTable;");
In the exception info I see it's caused by "SELECT #unique_id := MAX(UniqueID) FROM SomeTable;" line. Here is the full exception info:
Exception in thread "main" java.sql.SQLSyntaxErrorException: (conn:29) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT #unique_id := MAX(UniqueID) FROM SomeTable' at line 4
Why does this happen and how to make it work?

Resultset throws syntax error when there are no records in database

Below I show my sql query which is dynamic in Java.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -365);
Adjust to 12 months before current month with 0 hrs and min
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
String lastYearTime = String.valueOf(cal.getTimeInMillis() / 1000);
while(iterator.hasNext())
{
tablename = Database.getTableName((String)iterator.next());
fields = "status,count(*) as count";
query.append("select " + fields + " from " + tablename + " where");
query.append(" toid ='" + collegeId + "'");
query.append(" and dtstamp >='" + lastYearTime + "'");
query.append(" group by status");
if(i.hasNext())
query.append(" UNION ");
}
StringBuffer countquery = new StringBuffer("select status, SUM(count) as count from ( " + query + ")as temp group by status ");
ResultSet rs = Database.executeQuery(countquery.toString(), connection);
In the above query, tablename will be random based on other factors. collegeId can be any id. Status can be like dropout,pursuing or any random status.
When I execute my above query, result set works fine and data is displayed. But when there are no records in the database then it throws a sql syntax error 1064 stating
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 ')as temp group by status' at line 1
Problem1
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 ')as temp group by status' at line 1
You have a problem in your query:
select status, SUM(count) as count from ( " + query + ")as temp group by status
You should to make a space in your query here :
from ( " + query + ")as
replace this ")as with this ") as
EDIT
Problem2
SQL Exception : 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 ') as temp group by status' at line 1 SQL State : 42000 Error Code : 1064
Your query is a String so you should to put it between two 'query'
now replace this :
select status, SUM(count) as count from ( " + query + ")as temp group by status
By this :
select status, SUM(count) as count from ( '" + query + "') as temp group by status
Good luck.
Resultset throws syntax error when there are no records in database
No it doesn't. It throws a syntax-error exception when you have a syntax error in your query.

Want to convert and SQL to Hibernate Query Language

I have a requirement where I have to convert an SQL to HQL.
The SQL query is as follows:
select RT.tableNumber, temp.confirmationNumber from ReservationTable RT, (select R.tableNumber, R.confirmationNumber from Reservation R where R.date = 'someDate' and R.time = 'someTime' and R.reservationStatus = 'CONFIRMED') as temp where RT.tableNumber = temp.tableNumber and RT.tableNumber = 'someTableNumber' ;
I tried converting it to the following HQL:
select RT.tableNumber, temp.confirmationNumber from ReservationTable RT, (select R.tableNumber, R.confirmationNumber from Reservation R where R.date = :param1 and R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3";
But when I run this HQL through Eclipse, I get the below error lines:
ERROR: line 1:102: unexpected token: (
ERROR: line 1:146: unexpected token: from
SEVERE: Servlet.service() for servlet [dispatcher] in context with
path [/RRSRestApp] threw exception [Request processing failed; nested
exception is org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 102 [select RT.tableNumber,
temp.confirmationNumber from
com.kartik.restaurant.model.ReservationTable RT, (select
R.tableNumber, R.confirmationNumber from
com.kartik.restaurant.model.Reservation R where R.date = :param1 and
R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where
RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3; ]]
with root cause org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 102 [select RT.tableNumber,
temp.confirmationNumber from
com.kartik.restaurant.model.ReservationTable RT, (select
R.tableNumber, R.confirmationNumber from
com.kartik.restaurant.model.Reservation R where R.date = :param1 and
R.time = :param2 and R.reservationStatus = 'CONFIRMED') as temp where
RT.tableNumber = temp.tableNumber and RT.tableNumber = :param3; ]
Can anyone help me with this?
According to hibernate documentation HQL subqueries can occur only in the select or where clauses.
for more detail please follow hibernate documentation

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: start near line 1, column 84

I am getting an error while executing the query. The error is:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: start near line 1, column 84 [from com.services.om.entity.OrderLines where orderNumber in (:order_Numbers) start with parentLineIdentifier is null connect by prior orderLineIdentifier = parentLineIdentifier]
My DAO code is :
public List<OrderLineVO> findAllOrders(List<BigDecimal> orderNumbers) throws OrderManagementException {
try{
String getAllOrders = "from OrderLines where orderNumber in (:order_Numbers) order by orderDate desc ";
Query query = em.createQuery(getAllOrders,OrderLines.class);
query.setParameter("order_Numbers", orderNumbers);
List<OrderLines> orderLinesList = query.getResultList();
String queryParentChild = "from OrderLines where orderNumber in (:order_Numbers) start with parentLineIdentifier is null connect by prior orderLineIdentifier = parentLineIdentifier";
Query queryParent = em.createQuery(queryParentChild, OrderLines.class);
queryParent.setParameter("order_Numbers", orderNumbers);
List<OrderLines> orderLinesList2 = queryParent.getResultList();
return OrderLineUTIL.getOrderLines(orderLinesList);
}catch(Exception exception){
logger.error(exception.getMessage());
throw new OrderManagementException(exception.getMessage());
}
}
em.createQuery(queryParentChild, OrderLines.class); // Line is giving above error.
Any Suggestion ?
Also the entity class field variables are marked correctly in query.

JDBC error but no error when I run my query in MySQL workbench

I am running a query on a MySQL database, I am using JDBC and I am using MySQL workbench to run the query.
When I run it in MySQL work bench I get what I was expecting but when I run it in my code 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 'SELECT Character.CharacterID, Character.CharacterName, Characte' at line 1
Here is the Java:
for (int i = 0; i < 3; i++) {
try {
result = s.executeQuery("USE `arbitrary-hero`; SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), "
+ "SUM(ItemStrength), SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON `Character`.CharacterID = Character_Items.CharacterID INNER JOIN "
+ "Items ON Character_Items.ItemID = Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "+ name[i] +" GROUP BY `Character`.CharacterName;;");
}
catch(Exception e) {
System.out.println(e);
}
}
s.close();
Here is the SQL:
SELECT `Character`.CharacterID, `Character`.CharacterName, `Character`.CharacterLevel, SUM(ItemAttack), SUM(ItemHealth), SUM(ItemAgility), SUM(ItemStrength),
SUM(ItemSource) FROM `arbitrary-hero`.`Character` INNER JOIN `arbitrary-hero`.Character_Items ON
`Character`.CharacterID = Character_Items.CharacterID INNER JOIN Items ON
Character_Items.ItemID= Items.ItemID WHERE Character_Items.Equiped = 1 and `Character`.CharacterName = "Maxinfet" GROUP BY `Character`.CharacterName;
Not sure, but I think you can't use two SQL commands together, so everything after the semi-colon is an error.

Categories