title: Hibernate null constraint violation on @Id with @GeneratedValue
body: <p>I am using Hibernate 4.1.3 (JPA) on the Play! framework. The database is PostgreSQL 8.4.2. The schema was generated using <code>hibernate.hbm2ddl.auto="update"</code>.</p>
  
  <p>Short version: I have a class that has an <code>@Id</code> field that is a <code>@GeneratedValue</code>. Sometimes, when <code>persist</code>ing it, I get a null-column violation, why?</p>
  
  <hr>
  
  <p>More details:</p>
  
  <p>I have a really simple class that I want to save to the database, that looks like this:</p>
  
  <pre><code>@Entity
  class MyObject {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      public Long id;
  
      @NotNull
      public String email;
  
      public Integer total;
  }
  </code></pre>
  
  <p>I usually create an instance of MyObject, I assign a value to <code>email</code> and <code>total</code> fields while <code>id</code> is null and I save it via <code>EntityManager.persist()</code>. Hibernate gets an id for the new object and saves it to the DB.</p>
  
  <p>However sometimes, I get the following stacktrace:</p>
  
  <pre><code>2012-05-19 00:45:16,335 - [ERROR] - from org.hibernate.engine.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:144] in play-akka.actor.actions-dispatcher-6 
  ERROR: null value in column "id" violates not-null constraint
  
  2012-05-19 00:45:16,350 - [ERROR] - from application in play-akka.actor.actions-dispatcher-6 
  
  
  ! @6ad7j3p8p - Internal server error, for request [POST /method] -&gt;
  
  play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[PersistenceException: org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "id" violates not-null constraint]]
  </code></pre>
  
  <p>How is this possible? How can I track down the problem?</p>
  
  <p>Here's the relevant DDL generated by Hibernate:</p>
  
  <pre><code>CREATE TABLE myobject (
      id bigint NOT NULL,
      email character varying(255) NOT NULL,
      physical integer
  );
  
  CREATE SEQUENCE hibernate_sequence
      START WITH 1
      INCREMENT BY 1
      NO MAXVALUE
      NO MINVALUE
      CACHE 1;
  
  
  ALTER TABLE ONLY dailydetailedscore
      ADD CONSTRAINT dailydetailedscore_pkey PRIMARY KEY (id);
  </code></pre>