实现一个自定义的IdentifierGenerator类;从博客文章:
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 pre 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; }}像这样注释实体PK:
@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;}由于Eclipse中的错误,可能会引发一个错误,即
seq_id在持久性单元中未定义generator()。将此设置为警告,如下所示:
- 选择 窗口»首选项
- 展开 Java持久性»JPA»错误/警告
- 点击 查询和生成器
- 在持久性单元中未 将Set Generator定义 为:
Warning
- 单击 确定 以应用更改并关闭对话框



