为什么Hibernate不使用H2 DB的序列?

时间:2018-03-28 21:33:39

标签: hibernate sequence h2

我正在使用Hibernate 5.2.15和H2数据库(版本1..4.197)。我用

创建了一个序列
CREATE SEQUENCE SEQ_PRIMARYKEY START WITH 1 INCREMENT BY 1;

我的实体看起来像

@Entity
@Table(name="Payment", 
   uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class Payment {

    @Id
    @SequenceGenerator(name="seq_PK",sequenceName="SEQ_PRIMARYKEY")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_PK")      
    @Column(name="ID", nullable=false, unique=true, length=11)
    private int id;
...
}

DAO实现如下

@Override
public void persist(T entity) {
    currentSession = HibernateUtil.getSessionFactory().getCurrentSession();
    currentTransaction = currentSession.beginTransaction();
    currentSession.save(entity);
    currentTransaction.commit();
    currentSession.close();
}

在数据库中,序列的当前值例如是190,但是当持久存在时,实体的id为78。 我希望ID与序列的下一个值匹配。我的期望是错的吗? 我如何更改实现以满足我的期望?

编辑:停止Tomcat时,我收到以下警告:

WARNUNG: The web application [myApp] appears to have started a thread named    [pool-1-thread-1] but has failed to stop it. This is very likely to create a   memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
     java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos   (Unknown Source)
 java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 java.lang.Thread.run(Unknown Source)

也许它与某种程度有关?

Edit2:删除表格和序列后,现在它似乎是同步的,但它可能只是一个快乐的事故。虽然序列应该以1开始,但是我坚持使用的是ID“-46”,而不是1,这是我所期望的。为什么呢?

1 个答案:

答案 0 :(得分:0)

问题herehere与我的非常相似,设置属性allocationSize = 1解决了我的问题。另一方面,设置<property value="true" name="hibernate.id.new_generator_mappings"/>没有效果。