【问题标题】:org.hibernate.HibernateException in a basic hibernate program基本休眠程序中的 org.hibernate.HibernateException
【发布时间】:2011-03-30 20:39:55
【问题描述】:

我收到以下错误session.save(student);

org.hibernate.HibernateException: The database returned no natively generated identity value

这里是主要功能

{
  BasicConfigurator.configure();
  Session session = HibernateUtil.getSessionFactory().openSession();
  Transaction transaction = null;
  try {
   transaction = session.beginTransaction();
   Address address = new Address("Outer Ring Road", "Delhi", "TN", "110001");
   Student student = new Student("kumar", address);
   session.save(student);
   transaction.commit();
     } catch (HibernateException e) {

   if (transaction != null) {
      transaction.rollback();

    }
   e.printStackTrace();
  } finally {
   session.close();
 }
}

【问题讨论】:

  • 你的SGBD叫什么名字?
  • 我正在使用 MySQL Workbench 5.2 CE 数据库。驱动类是 com.mysql.jdbc.Driver
  • 你能发布你用来映射学生和地址类的映射吗?这有助于调试您的问题。
  • 在询问 Hibernate 问题时:告诉我们您使用什么 DB/Dialect,发布您的映射、表格、确切的堆栈跟踪。

标签: java mysql hibernate orm


【解决方案1】:

我遇到了同样的问题,在键上设置自动增量解决了它。

【讨论】:

    【解决方案2】:

    MySQL 是否支持本机生成器:

    <id name="userID" column="userID">
      <generator class="native"/>
    </id>
    

    但这假设表是使用 ID 列上的 AUTO_INCREMENT 属性创建的,以便为新行生成唯一标识。

    CREATE TABLE animals (
         id MEDIUMINT NOT NULL AUTO_INCREMENT,
         name CHAR(30) NOT NULL,
         PRIMARY KEY (id)
     );
    

    您应该让SchemaExport 为您生成 DDL。

    参考

    【讨论】:

      【解决方案3】:

      我的第一个猜测是您的数据库不支持本地生成的标识符。您必须在映射文件中为主键指定除“native”(默认值)以外的生成器。

      尝试“增量”,这告诉 Hibernate 处理标识符生成而不是依赖数据库。但请记住,它不适用于集群:

      <id name="...">
          <column name="..." />
          <generator class="increment" />
      </id>
      

      【讨论】:

        猜你喜欢
        • 2011-03-30
        • 2017-11-14
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 2012-10-31
        • 1970-01-01
        相关资源
        最近更新 更多