实现一个自定义的 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 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;
}
}
像这样注释实体 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
) 未在持久性单元中定义。将其设置为警告,如下所示:
- 选择窗口 » 首选项
- 展开Java 持久性 » JPA » 错误/警告
- 单击查询和生成器
- Set Generator 未在持久性单元中定义为:
Warning
- 单击确定以应用更改并关闭对话框