我有一个实体,它有一个NON-ID字段,必须从序列中设置。目前,我获取序列的第一个值,将其存储在客户端,并根据该值进行计算。
然而,我正在寻找一种"更好"的方式来做到这一点。我已经实现了一种获取下一个序列值的方法:
public Long getNextKey()
{
Query query = session.createSQLQuery( "select nextval('mySequence')" );
Long key = ((BigInteger) query.uniqueResult()).longValue();
return key;
}
然而,这种方式会显著降低性能(大约5000个对象的创建速度会降低3倍,从5740ms降低到13648ms)。
我试图添加一个"假的"实体:
@Entity
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class SequenceFetcher
{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private long id;
public long getId() {
return id;
}
}
然而,这种方法也不起作用(返回的所有Id都是0)。
有人能告诉我如何使用Hibernate有效地获取下一个序列值吗?
编辑:经过调查,我发现调用Query query = session.createSQLQuery( "select nextval('mySequence')" );
比使用@GeneratedValue
效率低得多,因为Hibernate在某种程度上在访问@GeneratedValue
描述的序列时能够减少获取次数。
例如,当我创建70000个实体时(因此从同一序列中提取了70000个主键),我得到了所需的一切。
HOWEVER,Hibernate只发出1404select nextval ('local_key_sequence')
命令。注意:在数据库端,缓存设置为1。
如果我尝试手动获取所有数据,将需要70000次选择,因此性能上存在巨大差异。有人知道Hibernate的内部功能吗?以及如何手动复制它?
您可以使用Hibernate方言API实现数据库独立性,如下所示
class SequenceValueGetter {
private SessionFactory sessionFactory;
// For Hibernate 3
public Long getId(final String sequenceName) {
final List<Long> ids = new ArrayList<Long>(1);
sessionFactory.getCurrentSession().doWork(new Work() {
public void execute(Connection connection) throws SQLException {
DialectResolver dialectResolver = new StandardDialectResolver();
Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
resultSet = preparedStatement.executeQuery();
resultSet.next();
ids.add(resultSet.getLong(1));
}catch (SQLException e) {
throw e;
} finally {
if(preparedStatement != null) {
preparedStatement.close();
}
if(resultSet != null) {
resultSet.close();
}
}
}
});
return ids.get(0);
}
// For Hibernate 4
public Long getID(final String sequenceName) {
ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
@Override
public Long execute(Connection connection) throws SQLException {
DialectResolver dialectResolver = new StandardDialectResolver();
Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getLong(1);
}catch (SQLException e) {
throw e;
} finally {
if(preparedStatement != null) {
preparedStatement.close();
}
if(resultSet != null) {
resultSet.close();
}
}
}
};
Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
return maxRecord;
}
}
以下是对我有效的方法(特定于Oracle,但使用scalar
似乎是关键)
Long getNext() {
Query query =
session.createSQLQuery("select MYSEQ.nextval as num from dual")
.addScalar("num", StandardBasicTypes.BIG_INTEGER);
return ((BigInteger) query.uniqueResult()).longValue();
}
感谢这里的海报:springsource_forum
我找到了解决方案:
public class DefaultPostgresKeyServer
{
private Session session;
private Iterator<BigInteger> iter;
private long batchSize;
public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
{
this.session=sess;
batchSize = batchFetchSize;
iter = Collections.<BigInteger>emptyList().iterator();
}
@SuppressWarnings("unchecked")
public Long getNextKey()
{
if ( ! iter.hasNext() )
{
Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );
iter = (Iterator<BigInteger>) query.list().iterator();
}
return iter.next().longValue() ;
}
}
如果使用Oracle,请考虑为序列指定缓存大小。如果你经常以5K的批量创建对象,你可以将其设置为1000或5000。我们对用于代理主键的序列进行了此操作,并惊讶于用Java手工编写的ETL进程的执行时间减少了一半。
我无法将格式化的代码粘贴到注释中。以下是DDL:序列
create sequence seq_mytable_sid
minvalue 1
maxvalue 999999999999999999999999999
increment by 1
start with 1
cache 1000
order
nocycle;
要获得新的id,您所要做的就是flush
实体管理器。参见下面的getNext()
方法:
@Entity
@SequenceGenerator(name = "sequence", sequenceName = "mySequence")
public class SequenceFetcher
{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
private long id;
public long getId() {
return id;
}
public static long getNext(EntityManager em) {
SequenceFetcher sf = new SequenceFetcher();
em.persist(sf);
em.flush();
return sf.getId();
}
}
POSTGRESQL
String psqlAutoincrementQuery = "SELECT NEXTVAL(CONCAT(:psqlTableName, '_id_seq')) as id";
Long psqlAutoincrement = (Long) YOUR_SESSION_OBJ.createSQLQuery(psqlAutoincrementQuery)
.addScalar("id", Hibernate.LONG)
.setParameter("psqlTableName", psqlTableName)
.uniqueResult();
MYSQL
String mysqlAutoincrementQuery = "SELECT AUTO_INCREMENT as id FROM information_schema.tables WHERE table_name = :mysqlTableName AND table_schema = DATABASE()";
Long mysqlAutoincrement = (Long) YOUR_SESSION_OBJ.createSQLQuery(mysqlAutoincrementQuery)
.addScalar("id", Hibernate.LONG)
.setParameter("mysqlTableName", mysqlTableName)
.uniqueResult();
有趣的是,它对您有效。当我尝试您的解决方案时,出现了一个错误,说"类型不匹配:无法从SQLQuery转换为Query"。-->因此,我的解决方案看起来像:
SQLQuery query = session.createSQLQuery("select nextval('SEQUENCE_NAME')");
Long nextValue = ((BigInteger)query.uniqueResult()).longValue();
使用该解决方案,我没有遇到性能问题。
如果你只是想了解信息,不要忘记重置你的价值。
--nextValue;
query = session.createSQLQuery("select setval('SEQUENCE_NAME'," + nextValue + ")");
Spring 5有一些内置的助手类:org/springframework/jdbc/support/incrementer
以下是我的操作方法:
@Entity
public class ServerInstanceSeq
{
@Id //mysql bigint(20)
@SequenceGenerator(name="ServerInstanceIdSeqName", sequenceName="ServerInstanceIdSeq", allocationSize=20)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ServerInstanceIdSeqName")
public Long id;
}
ServerInstanceSeq sis = new ServerInstanceSeq();
session.beginTransaction();
session.save(sis);
session.getTransaction().commit();
System.out.println("sis.id after save: "+sis.id);
您使用SequenceGenerator伪实体的想法很好。
@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
@org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")
使用键名为"sequence_name"的参数非常重要。在hibernate类SequenceStyleGenerator上运行调试会话,在final QualifiedName sequenceName=determineSequenceName(params,方言,jdbcEnvironment)行的configure(…)方法;以查看有关Hibernate如何计算序列名的更多详细信息。这里有一些默认值,你也可以使用。
在伪造实体之后,我创建了一个CrudRepository:
public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}
在Junit中,我调用SequenceRepository的save方法。
SequenceGenerator sequenceObject=新SequenceGenerator();SequenceGenerator结果=sequenceRepository.save(sequenceObject);
如果有更好的方法可以做到这一点(也许在任何类型的字段上支持生成器,而不仅仅是Id),我会非常乐意使用它来代替这个"技巧"。