MyBatis java and MySql local variables - java

I'm new to java world. And I have a problem with simple query:
<insert id="create" parameterType="models.entities.CategoryEntity">
set #catId := (select categoryId from Categories limit 1);
insert into Categories(CategoryId, Title, LeftValue, RightValue)
values(#catId, 'Test in', 1,2);
....
</insert>
it simply fails when i trying to run it with mybatis:
PersistenceException occured : ### Error updating database. Cause: 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 'insert into Categories(CategoryId, Title, LeftValue, RightValue) values(' at line 2 ### The error may involve Category.create-Inline ### The error occurred while setting parameters ### Cause: 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 'insert into Categories(CategoryId, Title, LeftValue, RightValue) values(' at line 2
If I remove this line:
set #catId := (select categoryId from Categories limit 1);
then everything is ok. What am i doing wrong? Is it problem with jdbc or mybatis? How to use mysql #variables with mybatis? Does someone have examples of using MySql local variables with mybatis?

I found out how to get it worked. Just set datasource property allowMultiQueries=true
jdbc:mysql://localhost:3306/DBS?allowMultiQueries=true

Related

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

What is causing this exception, I have used the similar approach in a UserController and that worked fine. Is the mapping of SQL table with Entity Classes wrong ?
I can't store data and I can't retrieve anything from it either. It keeps giving me the same error, Initially I though my Latitude and Longitude might be wrong but then I tried inserting a simple user_id and is being rejected too.
Controller
#Autowired
OrderMapper orderMapper;
#ResponseBody
#RequestMapping(value = "/getOrder", method = RequestMethod.POST)
public Order PlaceOrder()
{
Order order = new Order();
order.setUserId(1);
orderMapper.insert(order);
return order;
}
OrderMapper
<insert id="insert" parameterType="com.mena.api.entity.Order">
insert into order (order_id, user_id, start_latitude,
start_logitude, end_latitude, end_logitude,
total_distance, type, cost,
create_time, start_address, end_address,
user_id2)
values (#{orderId,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{startLatitude,jdbcType=DECIMAL},
#{startLogitude,jdbcType=DECIMAL}, #{endLatitude,jdbcType=DECIMAL}, #{endLogitude,jdbcType=DECIMAL},
#{totalDistance,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{cost,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP}, #{startAddress,jdbcType=VARCHAR}, #{endAddress,jdbcType=VARCHAR},
#{userId2,jdbcType=INTEGER})</insert>
And SQL Table Info
Error Log
</pre><p><b>Root Cause</b></p><pre>org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: 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 'order
where order_id = 1' at line 6
### The error may exist in file [\khadim\khadimApi\khadimApi\target\khadminapi\WEB-INF\classes\mybatis\OrderMapper.xml]
### The error may involve com.mena.api.mapper.OrderMapper.selectByPrimaryKey-Inline
### The error occurred while setting parameters
### SQL: select 'true' as QUERYID, order_id, user_id, start_latitude, start_logitude, end_latitude, end_logitude, total_distance, type,
cost, create_time, start_address, end_address, user_id2 from order where order_id = ?
### Cause: 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 'order
where order_id = 1' at line 6
; bad SQL grammar []; nested exception is 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 'order
where order_id = 1' at line 6
org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235)
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
com.sun.proxy.$Proxy35.selectOne(Unknown Source)
org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:167)
org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:82)
org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
com.sun.proxy.$Proxy36.selectByPrimaryKey(Unknown Source)
com.mena.api.controller.OrderController.PlaceOrder(OrderController.java:34)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
order is a reserved word in MySql, this is why your select ... from order probably fails with that exception. If order really is the table name in your database, you could escape it as follows:
select ... from `order` ...
Or better yet would be to use a non-reserved table name, like 'orders'.

Hibernate generating wrong sql syntax

Hibernate generating wrong sql(MySQL) query with syntax error.
given this HQL query :
"update GpClientContacter set id = :newKey where id = :Key"
Hibernate executes this sql query:
Hibernate: update GP_CLIENT_CONTACTER set CODE_CLIENT, NOM_RS=(?, ?) where (CODE_CLIENT, NOM_RS)=(?, ?)
Here is exception message:
ERROR: 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 ' NOM_RS=(15, 'test1') where (CODE_CLIENT, NOM_RS)=(15, 'test5')' at line 1
.
.
org.hibernate.exception.SQLGrammarException: could not execute statement
id is an EmbeddedId that has the codeClient and nomRs fields. :key and :newKey are instances of the EmbeddedId Type

HIVE and myBatis issue with Date/Timestamp fields

I've code a simple hadoop/hive table defined as
CREATE TABLE mike
timeOne TIMESTAMP,
timeTwo TIMESTAMP,
name STRING
And then a myBatis mapper file to insert a record here that looks like this
<insert id="insertMikeFormDataForHadoop" parameterType="hashmap">
INSERT INTO ${tableName} (timeOne, timeTwo, name)
VALUES (#{timeOne, jdbcType=DATE}, #{timeTwo, jdbcType=DATE}, #{name})
</insert>
When I run a test to insert data via this SQL I get error like this.
org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 2:16 mismatched input '-' expecting ) near '2017' in value row constructor
### The error may involve com.vertexinc.ve.returns.mapper.FormMapper.insertMikeFormDataForHadoop-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO mike (timeOne, timeTwo, name) VALUES (?, ?, ?)
### Cause: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 2:16 mismatched input '-' expecting ) near '2017' in value row constructor
I've also tried this with jdbcType=TIMESTAMP instead of date with the same error.
I've wondering if I'm doing something wrong or assuming something about hive/hadoop and mybatis that I shouldn't.
(This is a super simple example I've used to illustrate this point).
Turns out this was an issue with the hive jdbc driver version 1.2.1.
The setTimestamp in the HivePreparedStatement had a small defect. Upgrading driver fixed the issue..
https://issues.apache.org/jira/browse/HIVE-11748

Why can't I set a variable in a prepared statement in MySQL?

I'm running a script to insert some data in a MySQL database, and it runs properly in the MySQL workbench. However, when I try to run it from Java via the JDBC, I get an error. The script is:
INSERT INTO `pa_record` (`username`, `pa_record_type`, `record_time`) VALUES (?, ?, CURRENT_TIMESTAMP);
SET #record_id := 1;
INSERT INTO `pa_crud` (`pa_record_id`, `table_name`) VALUES (#record_id, ?);
The error I get from the JDBC is
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 'SET #record_id := 1;
INSERT INTO pa_crud (pa_record_id, table_name) VALUES' at line 2
Any ideas?
Many (most?) database access libraries do not allow multiple statements in a single execute; those that do, usually need to have the feature activated with a setting change. It's likely not complaining about the SET, but that you had anything after the end of the first query at all.

SQL Invalid Syntax in Java but not in Workbench

Why does this statement work fine in workbench but not in Java.
SET #sqlstmt := IF( #exist <= 0, 'select ''INFO: Key does not exist.''', 'ALTER TABLE `SOMETABLE` DROP FOREIGN KEY `SOMEKEY`');
In Java I get
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 'SET #sqlstmt := IF( #exist <= 0, 'select ''INFO: Key does not exist.''', 'ALTER ' at line 1
It turned out to be the fact that multiple statements were being executed (separated by semicolons). In JDBC MYSQL you need allowMultiQueries=true

Categories

Resources