title: Using primary key from a sequence on hibernate
body: <p>How can a use primary key in hibernate from a Postgres sequence?
  I need the primary be autogenerated, and them how i can get the sequence value for use in Hibernate</p>
  
  <p>this is my code</p>
  
  <p>Mapped class</p>
  
  <pre><code>import java.io.Serializable;
  import java.util.Date;
  import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.SequenceGenerator;
  import javax.persistence.Table;
  import javax.persistence.Temporal;
  
  @Entity
  @Table(name="ensaio")
  public class Ensaio implements Serializable {
  
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ensaio_seq")
    @SequenceGenerator(name="ensaio_seq", sequenceName="ensaio_seq")
    @Column(name="ensaio_id")
    private long id;
    private String nome;
    @Column(nullable=false)
    private String modelo;
    private String site;
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date datadoensaio;
    private int qtdeFotos;
    private String fotografo;
  
    getter and setters...
  }
  </code></pre>
  
  <p>My DAO:</p>
  
  <pre><code>import java.util.List;
  import model.Ensaio;
  import org.hibernate.Query;
  import org.hibernate.Session;
  import org.hibernate.SessionFactory;
  import util.hibernate.HibernateUtil;
  
  public class HEnsaioDAO {
  
    private Session session;
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  
    public HEnsaioDAO() {
      session = sessionFactory.openSession();
    }
  
    public List&lt;Ensaio&gt; findAll(){
      Query query = session.createQuery("from Ensaio");
      return query.list();
    }
  
    public void insertEnsaio(Ensaio ensaio){
      session.save(ensaio);
    }
  
    //testing insertion
    public static void main(String[] args) {
      Ensaio e = new Ensaio();
      e.setModelo("Roberta Maria");
      e.setSite("dsestudio");
      e.setFotografo("Jose Sobrero");
      e.setNome("Dama das camelias");
  
      HEnsaioDAO dao = new HEnsaioDAO();
  
      dao.insertEnsaio(e);
  
  
      List&lt;Ensaio&gt; list = dao.findAll();
      for (Ensaio ensaio : list) {
        System.out.println(ensaio.getModelo());
        System.out.println(ensaio.getNome());
        System.out.println(ensaio.getFotografo());
      }
    }
  
  }
  </code></pre>
  
  <p>Nothing happens in database (Postgres 8.3).
  What wrong?
  Thanks</p>