/** * Return the JDBC DataSource used by this DAO. */ @Nullable public final DataSource getDataSource() { return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null); }
/** * Set the JDBC DataSource to be used by this DAO. */ public final void setDataSource(DataSource dataSource) { if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { this.jdbcTemplate = createJdbcTemplate(dataSource); initTemplateConfig(); } }
@Override public String getCurrentDBUrl() { DataSource ds = this.jt.getDataSource(); if (ds == null) { return StringUtils.EMPTY; } BasicDataSource bds = (BasicDataSource)ds; return bds.getUrl(); }
/** * Execute the given SQL script. * <p>Use with caution outside of a transaction! * <p>The script will normally be loaded by classpath. * <p><b>Do not use this method to execute DDL if you expect rollback.</b> * @param sqlResourcePath the Spring resource path for the SQL script * @param continueOnError whether or not to continue without throwing an * exception in the event of an error * @throws DataAccessException if there is an error executing a statement * @see ResourceDatabasePopulator * @see #setSqlScriptEncoding */ protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { DataSource ds = this.jdbcTemplate.getDataSource(); Assert.state(ds != null, "No DataSource set"); Assert.state(this.applicationContext != null, "No ApplicationContext available"); Resource resource = this.applicationContext.getResource(sqlResourcePath); new ResourceDatabasePopulator(continueOnError, false, this.sqlScriptEncoding, resource).execute(ds); }
/** * Execute the given SQL script. * <p>Use with caution outside of a transaction! * <p>The script will normally be loaded by classpath. * <p><b>Do not use this method to execute DDL if you expect rollback.</b> * @param sqlResourcePath the Spring resource path for the SQL script * @param continueOnError whether or not to continue without throwing an * exception in the event of an error * @throws DataAccessException if there is an error executing a statement * @see ResourceDatabasePopulator * @see #setSqlScriptEncoding */ protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { DataSource ds = this.jdbcTemplate.getDataSource(); Assert.state(ds != null, "No DataSource set"); Assert.state(this.applicationContext != null, "No ApplicationContext set"); Resource resource = this.applicationContext.getResource(sqlResourcePath); new ResourceDatabasePopulator(continueOnError, false, this.sqlScriptEncoding, resource).execute(ds); }
public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler) { this.jdbcTemplate = jdbcTemplate; this.lobHandler = lobHandler; // 初始化transction this.transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 初始化一些数据 jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); databaseName = meta.getDatabaseProductName(); databaseMajorVersion = meta.getDatabaseMajorVersion(); databaseMinorVersion = meta.getDatabaseMinorVersion(); return null; } }); initTables(jdbcTemplate); }
/** * Prepare the given JDBC Statement (or PreparedStatement or CallableStatement), * applying statement settings such as fetch size, max rows, and query timeout. * @param stmt the JDBC Statement to prepare * @throws SQLException if thrown by JDBC API * @see #setFetchSize * @see #setMaxRows * @see #setQueryTimeout * @see org.springframework.jdbc.datasource.DataSourceUtils#applyTransactionTimeout */ protected void applyStatementSettings(Statement stmt) throws SQLException { int fetchSize = getFetchSize(); if (fetchSize != -1) { stmt.setFetchSize(fetchSize); } int maxRows = getMaxRows(); if (maxRows != -1) { stmt.setMaxRows(maxRows); } DataSourceUtils.applyTimeout(stmt, getDataSource(), getQueryTimeout()); }
@Override @Nullable public <T> T execute(ConnectionCallback<T> action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(obtainDataSource()); try { // Create close-suppressing Connection proxy, also preparing returned Statements. Connection conToUse = createConnectionProxy(con); return action.doInConnection(conToUse); } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. String sql = getSql(action); DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("ConnectionCallback", sql, ex); } finally { DataSourceUtils.releaseConnection(con, getDataSource()); } }
/** * Delegate method to perform the actual compilation. * <p>Subclasses can override this template method to perform their own compilation. * Invoked after this base class's compilation is complete. */ protected void compileInternal() { DataSource dataSource = getJdbcTemplate().getDataSource(); Assert.state(dataSource != null, "No DataSource set"); this.callMetaDataContext.initializeMetaData(dataSource); // Iterate over the declared RowMappers and register the corresponding SqlParameter this.declaredRowMappers.forEach((key, value) -> { this.declaredParameters.add(this.callMetaDataContext.createReturnResultSetParameter(key, value)); }); this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); if (logger.isDebugEnabled()) { logger.debug("Compiled stored procedure. Call string is [" + this.callString + "]"); } this.callableStatementFactory = new CallableStatementCreatorFactory( this.callString, this.callMetaDataContext.getCallParameters()); onCompileInternal(); }
/** * Delegate method to perform the actual compilation. * <p>Subclasses can override this template method to perform their own compilation. * Invoked after this base class's compilation is complete. */ protected void compileInternal() { DataSource dataSource = getJdbcTemplate().getDataSource(); Assert.state(dataSource != null, "No DataSource set"); this.tableMetaDataContext.processMetaData(dataSource, getColumnNames(), getGeneratedKeyNames()); this.insertString = this.tableMetaDataContext.createInsertString(getGeneratedKeyNames()); this.insertTypes = this.tableMetaDataContext.createInsertTypes(); if (logger.isDebugEnabled()) { logger.debug("Compiled insert object: insert string is [" + this.insertString + "]"); } onCompileInternal(); }
@Override @Nullable public <T> T execute(StatementCallback<T> action) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Connection con = DataSourceUtils.getConnection(obtainDataSource()); Statement stmt = null; try { stmt = con.createStatement(); applyStatementSettings(stmt); T result = action.doInStatement(stmt); handleWarnings(stmt); return result; } catch (SQLException ex) { // Release Connection early, to avoid potential connection pool deadlock // in the case when the exception translator hasn't been initialized yet. String sql = getSql(action); JdbcUtils.closeStatement(stmt); stmt = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("StatementCallback", sql, ex); } finally { JdbcUtils.closeStatement(stmt); DataSourceUtils.releaseConnection(con, getDataSource()); } }
JdbcUtils.closeStatement(ps); ps = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("PreparedStatementCallback", sql, ex); DataSourceUtils.releaseConnection(con, getDataSource());
JdbcUtils.closeStatement(cs); cs = null; DataSourceUtils.releaseConnection(con, getDataSource()); con = null; throw translateException("CallableStatementCallback", sql, ex); DataSourceUtils.releaseConnection(con, getDataSource());
@Test public void testTemplateConfiguration() { assertSame(dataSource, namedParameterTemplate.getJdbcTemplate().getDataSource()); }
protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { Resource resource = this.applicationContext.getResource(sqlResourcePath); new ResourceDatabasePopulator(continueOnError, false, this.sqlScriptEncoding, resource).execute(jdbcTemplate.getDataSource()); }
@Test @Transactional public void transactionalTest() { TransactionTestUtils.assertInTransaction(true); ClassPathResource resource = new ClassPathResource("/org/springframework/test/context/jdbc/data.sql"); new ResourceDatabasePopulator(resource).execute(jdbcTemplate.getDataSource()); assertNumUsers(1); }
protected void executeSqlScript(String sqlResourcePath) throws DataAccessException { Resource resource = applicationContext.getResource(sqlResourcePath); new ResourceDatabasePopulator(resource).execute(this.jdbcTemplate.getDataSource()); }
@Test public void testJdbcDaoSupportWithDataSource() throws Exception { DataSource ds = mock(DataSource.class); final List<String> test = new ArrayList<>(); JdbcDaoSupport dao = new JdbcDaoSupport() { @Override protected void initDao() { test.add("test"); } }; dao.setDataSource(ds); dao.afterPropertiesSet(); assertEquals("Correct DataSource", ds, dao.getDataSource()); assertEquals("Correct JdbcTemplate", ds, dao.getJdbcTemplate().getDataSource()); assertEquals("initDao called", 1, test.size()); }
@Test public void testBeanProperties() throws Exception { assertTrue("datasource ok", this.template.getDataSource() == this.dataSource); assertTrue("ignores warnings by default", this.template.isIgnoreWarnings()); this.template.setIgnoreWarnings(false); assertTrue("can set NOT to ignore warnings", !this.template.isIgnoreWarnings()); }
@Test public void parameterPropagation() { SqlOperation operation = new SqlOperation() {}; DataSource ds = new DriverManagerDataSource(); operation.setDataSource(ds); operation.setFetchSize(10); operation.setMaxRows(20); JdbcTemplate jt = operation.getJdbcTemplate(); assertEquals(ds, jt.getDataSource()); assertEquals(10, jt.getFetchSize()); assertEquals(20, jt.getMaxRows()); }