Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a string to DB sequence in Hibernate

Pretty much says it in the title. I have a class that looks something like this:

@Entity
@Table(name="FOO")
public class Foo {

  private String theId;

  @Id
  @Column(name = "FOO_ID")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "fooIdSeq")
  @SequenceGenerator(name = "fooIdSeq", sequenceName = "SQ_FOO_ID", allocationSize = 10)
  public String getTheId() { return theId; }

  public String setTheId(String theId) { this.theId = theId; }
}

Using Oracle 11g, the FOO_ID column is a VARCHAR2, but the sequence SQ_FOO_ID yields a NUMBER. The database is apparently happy with this, but the application needs to be able to support non-numeric IDs that may have been inserted into this column outside of the application.

Considering the code above, I get a org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String. Is there any way to do this mapping?

Using Hibernate 3.6.

like image 438
Andy Avatar asked Sep 20 '12 17:09

Andy


2 Answers

Implement a custom IdentifierGenerator class; from a blog post:

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;
    }
}

Annotate the entity PK like this:

@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;
}

Due to a bug in Eclipse, an error might be raised that the generator (seq_id) is not defined in the persistence unit. Set this to a warning as follows:

  1. Select Window » Preferences
  2. Expand Java Persistence » JPA » Errors/Warnings
  3. Click Queries and generators
  4. Set Generator is not defined in the persistence unit to: Warning
  5. Click OK to apply changes and close the dialog
like image 143
chris Avatar answered Oct 27 '22 07:10

chris


This is another approach:

import java.io.Serializable;

import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGeneratorHelper.BigDecimalHolder;
import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.id.SequenceGenerator;

public class StringSequenceGenerator extends SequenceGenerator {
    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        return super.generate( session, obj ).toString();
    }

    protected IntegralDataTypeHolder buildHolder() {
        return new BigDecimalHolder();
    }
}

The sequence parameter has to be specified on the id property like in the following example:

@Id
@GenericGenerator(name = "STRING_SEQUENCE_GENERATOR", strategy = "mypackage.StringSequenceGenerator", parameters = { @Parameter(name = "sequence", value = "MY_SEQUENCE_NAME") })
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STRING_SEQUENCE_GENERATOR")
@Column(name = "MY_ID")
public String getMyId() {
    return this.myId;
}
like image 31
Norbert Madarász Avatar answered Oct 27 '22 07:10

Norbert Madarász