Hibernate无需重命名即可保存实体

时间:2017-04-23 15:46:55

标签: java mysql hibernate

我有一个非常奇怪的问题,我无法理解它的原因。

我试图用只有1个字段(@id groupName),getter和setter来保存简单的Object(Group.class)。 当我尝试运行我的程序时,我有一个例外:

  

线程中的异常" main" org.hibernate.exception.SQLGrammarException:无法执行JDBC   

批量更新      

...

     

引起:java.sql.BatchUpdateException:你的错误   SQL语法;查看与MySQL服务器对应的手册   正确语法的版本,以便在' 组(groupName)值附近使用   ('测试')'在第1行

但是,如果我指定实体的名称(不同的组),一切正常。 你能解释一下我做错了吗?

代码:

的hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>

        <mapping class="com.globallogic.dto.Group"></mapping>


    </session-factory>

</hibernate-configuration>

import javax.persistence.*;

Group.class

@Entity //this doesn't work
//@Entity(name = "SomeName") // this works good
public class Group {

    @Id
    private String groupName;

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }
    public String getGroupName() {
        return groupName;

    }

}

DataSender.class

public class DataSender {
    private SessionFactory sessionFactory;
    public DataSender() {
        sessionFactory = new Configuration().configure()
                .buildSessionFactory();
    }
    public void sendData(Object... objects) {
        Session session = sessionFactory.openSession();
        if (session.isConnected()) {

            System.out.println("ALL IS GOOD");
            session.beginTransaction();

            for (Object user: objects) {
                session.persist(user);
            }
            System.out.println();
            session.getTransaction().commit();
            session.close();
            System.out.println("Connection is closed");
        }

        sessionFactory.close();
    }

}

Main.class

public class Main {

    public static void main(String[] args) {


        DataSender ds = new DataSender();

        Group group = new Group();
        group.setGroupName("Test");
        ds.sendData(group);

    }
}

1 个答案:

答案 0 :(得分:1)

Group是一个SQL关键字,您需要quote your table name

@Entity
@Table(name = "`Group`")
public class Group {
  ....