更新时出现休眠错误:无法执行语句,在 'index=1' 附近使用正确的语法
Posted
技术标签:
【中文标题】更新时出现休眠错误:无法执行语句,在 \'index=1\' 附近使用正确的语法【英文标题】:Hibernate error on update : could not execute statement, the right syntax to use near 'index=1'更新时出现休眠错误:无法执行语句,在 'index=1' 附近使用正确的语法 【发布时间】:2015-03-16 00:25:45 【问题描述】:我正在使用带有 Hibernate 和 mysql 的 netbeans 开发桌面应用程序。当我向数据库添加新记录时,它完全可以工作,但是当我尝试更新对象字段时出现此错误:
could not execute statement
INFO: HHH000010: On release of batch it still contained JDBC statements
Jan 17, 2015 2:47:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: SQL Warning Code: 1064, SQLState: 42000
Jan 17, 2015 2:47:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: 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 'index=1' at line 1
Java 代码:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
Session session = null;
try
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student student = (Student) session.get(Student.class, new Integer(1));
student.setMark(0);
System.out.println(student.getIndex()+" "+student.getName()+" "+student.getMark());
session.saveOrUpdate(student);
session.getTransaction().commit();
session.close();
catch (Exception e)
System.out.println(e.getMessage());
hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/studentsdb?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="entity/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
休眠映射xml:
<hibernate-mapping>
<class name="entity.Student" table="student" catalog="studentsdb">
<id name="index" type="java.lang.Integer">
<column name="index" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="20" not-null="true" />
</property>
<property name="surname" type="string">
<column name="surname" length="20" not-null="true" />
</property>
<property name="mark" type="double">
<column name="mark" precision="22" scale="0" not-null="true" />
</property>
</class>
</hibernate-mapping>
【问题讨论】:
您能否启用对休眠生成的实际 sql 语句的日志记录。见docs.jboss.org/hibernate/orm/4.3/topical/html/logging/… 【参考方案1】:INDEX is a reserved word 在 MySQL 和大多数其他关系数据库系统中。
您需要将标识符重命名为id
。
【讨论】:
是的,问题出在 id 列名“index”中。我将其更改为“id”后它正在工作。以上是关于更新时出现休眠错误:无法执行语句,在 'index=1' 附近使用正确的语法的主要内容,如果未能解决你的问题,请参考以下文章
示例数据 - “执行包含更新和插入语句的存储过程时出现问题”