Hibernate Annotation Error(org.hibernate.exception.SQLGrammarException:无法插入:[com.hib.ex.entity.Node])

时间:2014-07-06 22:18:05

标签: java hibernate hibernate-annotations

我是Hibernate Annotation的初学者,我想实现一个示例,但它给出了以下错误消息:

****************WRITING****************
log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into Node (group, name) values (?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.hib.ex.entity.Node]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
    at com.hib.ex.dao.HibExDao.saveNode(HibExDao.java:19)
    at com.hib.ex.main.Run.main(Run.java:18)
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 'group, name) values (null, 'zakaria')' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2643)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2362)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2280)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2265)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
    ... 17 more

这是实体类Node:

package com.hib.ex.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Node")
public class Node {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    @Column
    private String name;

    @Column
    private Integer group;

    public Node() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Node(Integer id, String name, Integer group) {
        super();
        this.id = id;
        this.name = name;
        this.group = group;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getGroup() {
        return group;
    }

    public void setGroup(Integer group) {
        this.group = group;
    }

}

这是DAO类HibExDao:

package com.hib.ex.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hib.ex.entity.HyperEdge;
import com.hib.ex.entity.Node;

public class HibExDao {

    public void saveNode(Node noeud) {

        SessionFactory sf = HibExUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        session.save(noeud);

        session.getTransaction().commit();
        session.close();

    }

    public List listNode() {

        SessionFactory sf = HibExUtil.getSessionFactory();
        Session session = sf.openSession();

        List nodes = session.createQuery("FROM Node").list();
        session.close();
        return nodes;

    }

    public Node readNode(Integer id) {

        SessionFactory sf = HibExUtil.getSessionFactory();
        Session session = sf.openSession();

        Node noeud = (Node) session.get(Node.class, id);
        session.close();
        return noeud;

    }

}

这是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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/exhiber</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>


        <mapping class="com.hib.ex.entity.Node" />
        <mapping class="com.hib.ex.entity.HyperEdge" />

    </session-factory>

</hibernate-configuration>

这是执行类Run:

package com.hib.ex.main;

import java.util.List;

import com.hib.ex.dao.HibExDao;
import com.hib.ex.entity.Node;

public class Run {


    public static void main(String[] args) {

        HibExDao dao = new HibExDao();

        System.out.println("****************WRITING****************");
        Node n1 = new Node();
        n1.setName("zakaria");
        dao.saveNode(n1);
        System.out.println("Node saved!");
        Node n2 = new Node();
        n2.setName("anas");
        dao.saveNode(n2);
        System.out.println("Node saved!");

        System.out.println("\n****************READING****************");
        List nodes = dao.listNode();
        System.out.println("Name in Node number 2 is: " + dao.readNode(2).getName());

    }

}

有什么问题?我能解决吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

明确提到了原因:

  

引起:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:   您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   在第1行附近'group,name)值(null,'zakaria')'

您的实体包含导致此问题的属性:

@Column
private Integer group;

答案很简单group是一个保留的SQL关键字(参见GROUP BY clause`)

要解决此问题,您需要重命名为列名并将其正确映射到您的实体属性。

此外,您没有填充group字段,因此它是NULL。也许MySQL不接受此列的NULL

我希望这会有所帮助。


如果要使用保留关键字,可以使用以下规范:

在JPA 2.0中:

@Column(name="\"group\"")

在Hibernate中:

@Column(name="'group'")

答案 1 :(得分:0)

要工作,您必须设置组属性或允许它为null(nullable = true)