Note that there are some explanatory texts on larger screens.

plurals
  1. POget next sequence value from database using hibernate
    text
    copied!<p>I have an entity that has an NON-ID field that must be set from a sequence. Currently, I fetch for the first value of the sequence, store it on the client's side, and compute from that value. </p> <p>However, I'm looking for a "better" way of doing this. I have implemented a way to fetch the next sequence value:</p> <pre><code>public Long getNextKey() { Query query = session.createSQLQuery( "select nextval('mySequence')" ); Long key = ((BigInteger) query.uniqueResult()).longValue(); return key; } </code></pre> <p>However, this way reduces the performance significantly (creation of ~5000 objects gets slowed down by a factor of 3 - from 5740ms to 13648ms ).</p> <p>I have tried to add a "fake" entity:</p> <pre><code>@Entity @SequenceGenerator(name = "sequence", sequenceName = "mySequence") public class SequenceFetcher { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence") private long id; public long getId() { return id; } } </code></pre> <p>However this approach didn't work either (all the Ids returned were 0).</p> <p>Can someone advise me how to fetch the next sequence value using Hibernate efficiently?</p> <p><strong>Edit:</strong> Upon investigation, I have discovered that calling <code>Query query = session.createSQLQuery( "select nextval('mySequence')" );</code> is by far more inefficient than using the <code>@GeneratedValue</code>- because of Hibernate <strong>somehow</strong> manages to reduce the number of fetches when accessing the sequence described by <code>@GeneratedValue</code>. </p> <p>For example, when I create 70,000 entities, (thus with 70,000 primary keys fetched from the same sequence), I get everything I need.</p> <p><strong>HOWEVER</strong> , Hibernate only issues <strong>1404</strong> <code>select nextval ('local_key_sequence')</code> commands. NOTE: On the database side, the caching is set to 1.</p> <p>If I try to fetch all the data manually, it will take me 70,000 selects, thus a huge difference in performance. Does anyone know the internal functioning of Hibernate, and how to reproduce it manually?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload