Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Implement a custom IdentifierGenerator class; from a <a href="http://blog.anorakgirl.co.uk/2009/01/custom-hibernate-sequence-generator-for-id-field/" rel="nofollow noreferrer">blog post</a>:</p> <pre><code>import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.id.IdentifierGenerator; public class StringKeyGenerator implements IdentifierGenerator { @Override public Serializable generate(SessionImplementor session, Object collection) throws HibernateException { Connection connection = session.connection(); PreparedStatement ps = null; String result = ""; try { // Oracle-specific code to query a sequence ps = connection.prepareStatement("SELECT TABLE_SEQ.nextval AS TABLE_PK FROM dual"); ResultSet rs = ps.executeQuery(); if (rs.next()) { int pk = rs.getInt("TABLE_PK"); // Convert to a String result = Integer.toString(pk); } } catch (SQLException e) { throw new HibernateException("Unable to generate Primary Key"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { throw new HibernateException("Unable to close prepared statement."); } } } return result; } } </code></pre> <p>Annotate the entity PK like this:</p> <pre><code>@Id @GenericGenerator(name="seq_id", strategy="my.package.StringKeyGenerator") @GeneratedValue(generator="seq_id") @Column(name = "TABLE_PK", unique = true, nullable = false, length = 20) public String getId() { return this.id; } </code></pre> <p>Due to a bug in Eclipse, an error might be raised that the generator (<code>seq_id</code>) is not defined in the persistence unit. Set this to a warning as follows:</p> <ol> <li>Select <strong>Window » Preferences</strong></li> <li>Expand <strong>Java Persistence » JPA » Errors/Warnings</strong></li> <li>Click <strong>Queries and generators</strong></li> <li>Set <strong>Generator is not defined in the persistence unit</strong> to: <code>Warning</code></li> <li>Click <strong>OK</strong> to apply changes and close the dialog</li> </ol>
 

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