简体   繁体   English

mariadb 序列 nextval 使用 hibernate 递增 2

[英]mariadb sequence nextval is incrementing by 2 using hibernate

I have a reference number and in that, for 3 digits I'm using a sequence.我有一个参考号,其中,对于 3 位数字,我使用的是一个序列。

I've created a sequence in MariaDB that starts from 111 will increment by 1 till 999 and then again start from 111. The strange thing is the sequence is incrementing by 2 instead of 1.我在 MariaDB 中创建了一个序列,它从 111 开始递增 1 直到 999,然后再次从 111 开始。奇怪的是序列递增 2 而不是 1。

The query for the sequence:查询序列:

CREATE SEQUENCE IF NOT EXISTS ref_seq START WITH 111 INCREMENT BY 1 MINVALUE=111 MAXVALUE=999 CYCLE ENGINE=INNODB

Below is the code下面是代码

Service

import org.springframework.stereotype.Service;
​
@Service
public interface SeqForIpe2RefNumService {
    int getSeqForIpe2Ref();
​
}

Service Impl

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
​
import com.test.ipe.batch.dao.SeqForIpe2RefNumDao;
@Service
public class SeqForIpe2RefNumServiceImpl implements SeqForIpe2RefNumService {
    private static final Logger logger = LoggerFactory.getLogger(SeqForIpe2RefNumServiceImpl.class);
    @Autowired
    SeqForIpe2RefNumDao seqForIpe2RefNumDao;
    @Override
    public int getSeqForIpe2Ref(){
        return seqForIpe2RefNumDao.getSeqForIpe2Ref();
    }
    
}

Dao

import org.springframework.stereotype.Repository;
​
@Repository
public interface SeqForIpe2RefNumDao {
    Integer getSeqForIpe2Ref();
}

DaoImpl

import java.math.BigInteger;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
​
@Repository
public class SeqForIpe2RefNumDaoImpl implements SeqForIpe2RefNumDao {
    
    private static final Logger logger = LoggerFactory.getLogger(SeqForIpe2RefNumDaoImpl.class);
​
    @Autowired
    private SessionFactory sessionFactory;
    @Override
    public Integer getSeqForIpe2Ref() {
        logger.info("In getSeqForIpe2Ref() :");
        Session session = sessionFactory.getCurrentSession();
        SQLQuery crit = session.createSQLQuery("SELECT NEXTVAL(IPE2REF_SEQ_BATCH)");
        BigInteger seqNbr = BigInteger.valueOf(0);
        if (crit.list().size() > 0) {
            seqNbr = (BigInteger) crit.list().get(0);
        }
        logger.info("SEQUENCE NUM :"+seqNbr.intValue());
        return seqNbr.intValue();
    }
}

You are executing your query twice:您正在执行两次查询:

if (crit.list().size() > 0) {   // <- first execution
   seqNbr = (BigInteger) crit.list().get(0); // <- second execution
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM