Oracle get multiple sequence values at a time

SQL statement to get multiple sequence values ​​at once

Get multiple values ​​in a sequence

create sequence

CREATE SEQUENCE test_user_seq;

get a sequence value

SELECT test_user_seq.nextval FROM dual;

insert image description here
There is a more traditional method to construct multi-row data, which is to use union all

SELECT 1 FROM DUAL
UNION ALL
SELECT 1 FROM DUAL

insert image description here
There is a method to generate multiple rows of data, so there is also a method to generate multiple sequences at a time

SELECT test_user_seq.nextval 
FROM (
SELECT 1 FROM DUAL
UNION ALL
SELECT 1 FROM DUAL)

insert image description here
To sum up, obtaining multiple sequence values ​​at a time requires generating multiple rows of data

connect by level generates multiple rows of data

The method of generating multi-row data by union all has relatively poor performance. When there are many sequences required, the SQL is relatively long, and the database takes a lot of time to parse the SQL, and it also needs to splicing SQL. Using connect by level to generate multi-row data
is relatively convenient

select level from dual connect by level <= 5;

insert image description here
5 rows of data are generated at a time, then you can use this method to obtain 5 sequence values

SELECT test_user_seq.nextval FROM (
select level from dual connect by level <= 5
);

insert image description here
Need to generate several sequence values, just modify the number of levels, very concise

JDBC get multiple sequence values ​​at once

Install the driver jar package to the local warehouse

  1. View the drive path of the Oracle installation directory
    insert image description here
  2. The maven command installs the driver jar to the local warehouse
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc8 -Dversion=19.0.0.0.0 -Dpackaging=jar -Dfile=H:\Oracle\19c\jdbc\lib\ojdbc8.jar
  1. Get multiple sequence values
import org.junit.Test;
import java.sql.*;
import java.util.Properties;

public class OracleJdbc {
    
    

    private static final String driver = "oracle.jdbc.driver.OracleDriver";

    private static final String url = "jdbc:oracle:thin:@localhost:1521/TEST";

    private static final String userName = "TEST_USER";

    private static final String password = "TEST_USER";

    static {
    
    
        // 加载驱动
        try {
    
    
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }

    public Connection createConnection(String url, String userName, String password) {
    
    
        Connection connection = null;
        try {
    
    
            connection = DriverManager.getConnection(url, userName, password);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return connection;
    }

    @Test
    public void testConnection() {
    
    
        Connection connection = createConnection(url, userName, password);
        try {
    
    
            Properties properties = connection.getClientInfo();
            System.out.println(properties);
            System.out.println(connection.getSchema());
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                connection.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testTestBatchSequence() {
    
    
        try (Connection connection = createConnection(url, userName, password)) {
    
    
            String sql = "SELECT test_user_seq.nextval FROM (select level from dual connect by level <= ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 5);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
    
    
                System.out.println(resultSet.getInt(1));
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}
  1. Run testTestBatchSequence, the result is as follows
48
49
50
51
52

MyBatis gets multiple sequence values ​​at a time

  1. Configuration file mybatis-config-oracle.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2017 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <!-- autoMappingBehavior should be set in each test case -->
    <properties resource="templates/oracle-db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"/>
                <property name="url" value="${jdbcUrl}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/OracleBatchSeqMapper.xml"/>
    </mappers>

</configuration>
  1. Mapper configuration file OracleBatchSeqMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.scd.mapper.OracleBatchSeqMapper">
    <select id="getBatchSeqId" resultType="java.lang.Long">
        SELECT test_user_seq.nextval FROM (select level from dual connect by level <![CDATA[ <= ]]> #{param})
    </select>
</mapper>
  1. Database configuration file oracle-db.properties
driverClassName=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521/TEST
username=TEST_USER
password=TEST_USER
  1. test code
import com.scd.mapper.OracleBatchSeqMapper;
import com.scd.mapper.TestUserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.Reader;
import java.util.List;

public class BatchSeqIdTest {
    
    

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
    
    
        String resource = "templates/mybatis-config-oracle.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }

    @Test
    public void testBatch() {
    
    
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
    
    
            OracleBatchSeqMapper oracleBatchSeqMapper = sqlSession.getMapper(OracleBatchSeqMapper.class);
            List<Long> idList = oracleBatchSeqMapper.getBatchSeqId(5);
            System.out.println(idList);
            Assert.assertEquals(5, idList.size());
        }
    }
}
  1. Execute the testBatch test method, and the running results are as follows
19:54:46.840 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
19:54:46.867 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
19:54:46.867 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
19:54:46.867 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
19:54:46.867 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - PooledDataSource forcefully closed/removed all connections.
19:54:46.969 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
19:54:47.971 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1766505436.
19:54:47.971 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@694abbdc]
19:54:47.975 [main] DEBUG com.scd.mapper.OracleBatchSeqMapper.getBatchSeqId - ==>  Preparing: SELECT test_user_seq.nextval FROM (select level from dual connect by level <= ?)
19:54:48.120 [main] DEBUG com.scd.mapper.OracleBatchSeqMapper.getBatchSeqId - ==> Parameters: 5(Integer)
19:54:48.209 [main] DEBUG com.scd.mapper.OracleBatchSeqMapper.getBatchSeqId - <==      Total: 5
[53, 54, 55, 56, 57]
19:54:48.210 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [oracle.jdbc.driver.T4CConnection@694abbdc]
19:54:48.210 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Closing JDBC Connection [oracle.jdbc.driver.T4CConnection@694abbdc]
19:54:48.210 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Returned connection 1766505436 to pool.

Guess you like

Origin blog.csdn.net/modelmd/article/details/128228962