Zyga
Zyga

Reputation: 2427

Hibernate multiple native SQL statements

I want to run a native SQL from a file using Hibernate. The SQL can contain several statements creating the database structure (i.e. tables, constraints but no insert/update/delete statements).

Example, very simple query is below (which contains the following two SQL statements)

CREATE DATABASE test;
CREATE TABLE test.testtbl( id int(5));

I am using MySQL db, and when I run the above query I am gettng syntax error returned. When I run them one by one, its ok.

Caused by: 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 
'CREATE TABLE test.testtbl( id int(5))' at line 1

The code to run the query is below (above statement is assigned to 'sql' variable):

session = sf.openSession();
session.beginTransaction();
Query qry = session.createSQLQuery(sql);
qry.executeUpdate();
session.getTransaction().commit();

Any help would be appreciated.

Upvotes: 0

Views: 3555

Answers (2)

demo
demo

Reputation: 111

The parameters of the method createSQLQuery is t-sql code; t-sql code to ensure that in the mysql interface analyzer correctly. You can try changed the sql :'CREATE TABLE testtbl(id int(5));' by the way you can use JDBC Connection api (Don't recommend to do so) Such as: java.sql.Connection conn=session.connection();

Upvotes: 0

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

As others have explained
You must run these queries one by one.
The hibernate code gets translated into running one update statement on JDBC.
But you provided two update statements.
In addition,
I personally prefer to have the code that creates tables outside of the Java application, in some DB scripts.

Upvotes: 1

Related Questions