Search in sources :

Example 11 with ConnectionCallback

use of org.springframework.jdbc.core.ConnectionCallback in project uPortal by Jasig.

the class RDBMUserLayoutStore method getNextStructId.

/**
 * Return the next available structure id for a user
 *
 * @return next free structure ID
 */
protected String getNextStructId(final IPerson person, final String prefix) {
    final int userId = person.getID();
    return nextStructTransactionOperations.execute(status -> jdbcOperations.execute(new ConnectionCallback<String>() {

        @Override
        public String doInConnection(Connection con) throws SQLException, DataAccessException {
            try (Statement stmt = con.createStatement()) {
                String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
                logger.debug("getNextStructId(): {}", sQuery);
                int currentStructId;
                try (ResultSet rs = stmt.executeQuery(sQuery)) {
                    if (rs.next()) {
                        currentStructId = rs.getInt(1);
                    } else {
                        throw new SQLException("no rows returned for query [" + sQuery + "]");
                    }
                }
                int nextStructId = currentStructId + 1;
                String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID=" + currentStructId;
                logger.debug("getNextStructId(): {}", sUpdate);
                stmt.executeUpdate(sUpdate);
                return prefix + nextStructId;
            }
        }
    }));
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) IJoinQueryString(org.apereo.portal.jdbc.IJoinQueryString)

Example 12 with ConnectionCallback

use of org.springframework.jdbc.core.ConnectionCallback in project spring-framework by spring-projects.

the class AbstractJdbcInsert method executeInsertAndReturnKeyHolderInternal.

/**
 * Delegate method to execute the insert, generating any number of keys.
 */
private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<?> values) {
    if (logger.isDebugEnabled()) {
        logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
        getJdbcTemplate().update(con -> {
            PreparedStatement ps = prepareStatementForGeneratedKeys(con);
            setParameterValues(ps, values, getInsertTypes());
            return ps;
        }, keyHolder);
    } else {
        if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
            throw new InvalidDataAccessResourceUsageException("The getGeneratedKeys feature is not supported by this database");
        }
        if (getGeneratedKeyNames().length < 1) {
            throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. " + "Using the generated keys features requires specifying the name(s) of the generated column(s)");
        }
        if (getGeneratedKeyNames().length > 1) {
            throw new InvalidDataAccessApiUsageException("Current database only supports retrieving the key for a single column. There are " + getGeneratedKeyNames().length + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
        }
        Assert.state(getTableName() != null, "No table name set");
        final String keyQuery = this.tableMetaDataContext.getSimpleQueryForGetGeneratedKey(getTableName(), getGeneratedKeyNames()[0]);
        Assert.state(keyQuery != null, "Query for simulating get generated keys must not be null");
        if (keyQuery.toUpperCase().startsWith("RETURNING")) {
            Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery, Long.class, values.toArray());
            Map<String, Object> keys = new HashMap<>(2);
            keys.put(getGeneratedKeyNames()[0], key);
            keyHolder.getKeyList().add(keys);
        } else {
            getJdbcTemplate().execute((ConnectionCallback<Object>) con -> {
                PreparedStatement ps = null;
                try {
                    ps = con.prepareStatement(getInsertString());
                    setParameterValues(ps, values, getInsertTypes());
                    ps.executeUpdate();
                } finally {
                    JdbcUtils.closeStatement(ps);
                }
                Statement keyStmt = null;
                ResultSet rs = null;
                try {
                    keyStmt = con.createStatement();
                    rs = keyStmt.executeQuery(keyQuery);
                    if (rs.next()) {
                        long key = rs.getLong(1);
                        Map<String, Object> keys = new HashMap<>(2);
                        keys.put(getGeneratedKeyNames()[0], key);
                        keyHolder.getKeyList().add(keys);
                    }
                } finally {
                    JdbcUtils.closeResultSet(rs);
                    JdbcUtils.closeStatement(keyStmt);
                }
                return null;
            });
        }
    }
    return keyHolder;
}
Also used : BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) Arrays(java.util.Arrays) Connection(java.sql.Connection) SqlTypeValue(org.springframework.jdbc.core.SqlTypeValue) SqlParameterSource(org.springframework.jdbc.core.namedparam.SqlParameterSource) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) KeyHolder(org.springframework.jdbc.support.KeyHolder) ArrayList(java.util.ArrayList) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) TableMetaDataContext(org.springframework.jdbc.core.metadata.TableMetaDataContext) SQLException(java.sql.SQLException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) JdbcUtils(org.springframework.jdbc.support.JdbcUtils) ResultSet(java.sql.ResultSet) Map(java.util.Map) InvalidDataAccessResourceUsageException(org.springframework.dao.InvalidDataAccessResourceUsageException) DataSource(javax.sql.DataSource) Nullable(org.springframework.lang.Nullable) PreparedStatement(java.sql.PreparedStatement) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) List(java.util.List) Statement(java.sql.Statement) StatementCreatorUtils(org.springframework.jdbc.core.StatementCreatorUtils) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) Collections(java.util.Collections) Assert(org.springframework.util.Assert) HashMap(java.util.HashMap) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) ResultSet(java.sql.ResultSet) InvalidDataAccessResourceUsageException(org.springframework.dao.InvalidDataAccessResourceUsageException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 13 with ConnectionCallback

use of org.springframework.jdbc.core.ConnectionCallback in project spring-boot by spring-projects.

the class AbstractDataSourcePoolMetadataTests method getPoolSizeTwoConnections.

@Test
public void getPoolSizeTwoConnections() {
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSourceMetadata().getDataSource());
    jdbcTemplate.execute(new ConnectionCallback<Void>() {

        @Override
        public Void doInConnection(Connection connection) throws SQLException, DataAccessException {
            jdbcTemplate.execute(new ConnectionCallback<Void>() {

                @Override
                public Void doInConnection(Connection connection) throws SQLException, DataAccessException {
                    assertThat(getDataSourceMetadata().getActive()).isEqualTo(2);
                    assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f);
                    return null;
                }
            });
            return null;
        }
    });
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 14 with ConnectionCallback

use of org.springframework.jdbc.core.ConnectionCallback in project uPortal by Jasig.

the class RDBMLocaleStore method updateUserLocales.

@Override
public void updateUserLocales(final IPerson person, final Locale[] locales) {
    this.transactionOperations.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {

                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    // Delete the existing list of locales
                    final String delete = "DELETE FROM UP_USER_LOCALE WHERE USER_ID=?";
                    PreparedStatement pstmt = con.prepareStatement(delete);
                    try {
                        pstmt.clearParameters();
                        pstmt.setInt(1, person.getID());
                        logger.debug(delete);
                        pstmt.executeUpdate();
                    } finally {
                        pstmt.close();
                    }
                    // Insert the new list of locales
                    final String insert = "INSERT INTO UP_USER_LOCALE VALUES (?, ?, ?)";
                    pstmt = con.prepareStatement(insert);
                    try {
                        for (int i = 0; i < locales.length; i++) {
                            pstmt.clearParameters();
                            pstmt.setInt(1, person.getID());
                            pstmt.setString(2, locales[i].toString());
                            pstmt.setInt(3, i);
                            logger.debug(insert);
                            pstmt.executeUpdate();
                        }
                    } finally {
                        pstmt.close();
                    }
                    return null;
                }
            });
        }
    });
}
Also used : Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) PreparedStatement(java.sql.PreparedStatement)

Example 15 with ConnectionCallback

use of org.springframework.jdbc.core.ConnectionCallback in project spring-boot by spring-projects.

the class AbstractDataSourcePoolMetadataTests method getPoolSizeTwoConnections.

@Test
void getPoolSizeTwoConnections() {
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSourceMetadata().getDataSource());
    jdbcTemplate.execute((ConnectionCallback<Void>) (connection) -> {
        jdbcTemplate.execute((ConnectionCallback<Void>) (connection1) -> {
            assertThat(getDataSourceMetadata().getActive()).isEqualTo(2);
            assertThat(getDataSourceMetadata().getUsage()).isEqualTo(1.0f);
            return null;
        });
        return null;
    });
}
Also used : Test(org.junit.jupiter.api.Test) DataSourceBuilder(org.springframework.boot.jdbc.DataSourceBuilder) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) ConnectionCallback(org.springframework.jdbc.core.ConnectionCallback) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) Test(org.junit.jupiter.api.Test)

Aggregations

ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)19 Connection (java.sql.Connection)13 PreparedStatement (java.sql.PreparedStatement)11 ResultSet (java.sql.ResultSet)11 SQLException (java.sql.SQLException)11 DataAccessException (org.springframework.dao.DataAccessException)9 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)9 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)6 Statement (java.sql.Statement)5 List (java.util.List)5 Date (java.sql.Date)4 Arrays (java.util.Arrays)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 DataSource (javax.sql.DataSource)4 IPerson (org.apereo.portal.security.IPerson)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 Test (org.junit.jupiter.api.Test)4 DataSourceBuilder (org.springframework.boot.jdbc.DataSourceBuilder)4 Cache (com.google.common.cache.Cache)3