views:

28

answers:

2

I get the following error session.save(student);

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

Here is main function

{
  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();
 }
}
A: 

My first guess is that your database doesn't support natively generated identifiers. You have to specify a generator other than "native" (which is the default) in your mapping file for your primary keys.

Try "increment", this tells Hibernate to handle the identifier generation instead of relying on the databse. Keep it mind however, that it won't work on clusters:

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

MySQL DOES support the native generator:

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

But this assumes the table has been created using an AUTO_INCREMENT attribute on the ID column to generate a unique identity for new rows.

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

You should let SchemaExport generate your DDL for you.

Reference

Pascal Thivent