休眠多个本地SQL语句 [英] Hibernate multiple native SQL statements

查看:135
本文介绍了休眠多个本地SQL语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Hibernate从文件运行本机SQL。 SQL可以包含多个创建数据库结构的语句(即表,约束,但不包含insert / update / delete语句)。

例子中,非常简单的查询在下面以下两条SQL语句)

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

我正在使用MySQL db,当我运行上述查询时,我返回了gettng语法错误。当我一个接一个地运行它时,它就OK。

 原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
您的SQL语法错误;检查与您的
MySQL服务器版本对应的手册,以便在第1行
'CREATE TABLE test.testtbl(id int(5))'附近使用正确的语法

$ b

运行查询的代码在下面(上面的语句被分配给'sql'变量):

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

任何帮助我们都会感激不尽。

解决方案

正如其他人所解释的一样
您必须逐个运行这些查询。
将hibernate代码翻译成在JDBC上运行一个更新语句。
但您提供了两条更新声明。 另外,
我个人更喜欢在一些数据库脚本中使用在Java应用程序之外创建表的代码。


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.

解决方案

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.

这篇关于休眠多个本地SQL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆