org.springframework.jdbc.core.JdbcTemplate.setDataSource()方法的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(155)

本文整理了Java中org.springframework.jdbc.core.JdbcTemplate.setDataSource()方法的一些代码示例,展示了JdbcTemplate.setDataSource()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JdbcTemplate.setDataSource()方法的具体详情如下:
包路径:org.springframework.jdbc.core.JdbcTemplate
类名称:JdbcTemplate
方法名:setDataSource

JdbcTemplate.setDataSource介绍

暂无

代码示例

代码示例来源:origin: spring-projects/spring-framework

/**
 * Set the JDBC {@link DataSource} to obtain connections from.
 * @see org.springframework.jdbc.core.JdbcTemplate#setDataSource
 */
public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate.setDataSource(dataSource);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Set the {@code DataSource}, typically provided via Dependency Injection.
 * <p>This method also instantiates the {@link #jdbcTemplate} instance variable.
 */
@Autowired
public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate.setDataSource(dataSource);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Set the {@code DataSource}, typically provided via Dependency Injection.
 * <p>This method also instantiates the {@link #jdbcTemplate} instance variable.
 */
@Autowired
public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate.setDataSource(dataSource);
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Construct a new JdbcTemplate, given a DataSource to obtain connections from.
 * <p>Note: This will not trigger initialization of the exception translator.
 * @param dataSource the JDBC DataSource to obtain connections from
 */
public JdbcTemplate(DataSource dataSource) {
  setDataSource(dataSource);
  afterPropertiesSet();
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Construct a new JdbcTemplate, given a DataSource to obtain connections from.
 * <p>Note: Depending on the "lazyInit" flag, initialization of the exception translator
 * will be triggered.
 * @param dataSource the JDBC DataSource to obtain connections from
 * @param lazyInit whether to lazily initialize the SQLExceptionTranslator
 */
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
  setDataSource(dataSource);
  setLazyInit(lazyInit);
  afterPropertiesSet();
}

代码示例来源:origin: alibaba/nacos

@Override
public boolean checkMasterWritable() {
  testMasterWritableJT.setDataSource(jt.getDataSource());
  /**
   *  防止login接口因为主库不可用而rt太长
   */
  testMasterWritableJT.setQueryTimeout(1);
  String sql = " SELECT @@read_only ";
  try {
    Integer result = testMasterWritableJT.queryForObject(sql, Integer.class);
    if (result == null) {
      return false;
    } else {
      return result.intValue() == 0 ? true : false;
    }
  } catch (CannotGetJdbcConnectionException e) {
    fatalLog.error("[db-error] " + e.toString(), e);
    return false;
  }
}

代码示例来源:origin: alibaba/nacos

@Override
  public void run() {
    defaultLog.info("check master db.");
    boolean isFound = false;
    int index = -1;
    for (BasicDataSource ds : dataSourceList) {
      index++;
      testMasterJT.setDataSource(ds);
      testMasterJT.setQueryTimeout(queryTimeout);
      try {
        testMasterJT
          .update("DELETE FROM config_info WHERE data_id='com.alibaba.nacos.testMasterDB'");
        if (jt.getDataSource() != ds) {
          fatalLog.warn("[master-db] {}", ds.getUrl());
        }
        jt.setDataSource(ds);
        tm.setDataSource(ds);
        isFound = true;
        masterIndex = index;
        break;
      } catch (DataAccessException e) { // read only
        e.printStackTrace(); // TODO remove
      }
    }
    if (!isFound) {
      fatalLog.error("[master-db] master db not found.");
      MetricsMonitor.getDbException().increment();
    }
  }
}

代码示例来源:origin: alibaba/nacos

jdbcTemplate.setDataSource(ds);

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testCouldNotGetConnectionForOperationWithLazyExceptionTranslator() throws SQLException {
  SQLException sqlException = new SQLException("foo", "07xxx");
  this.dataSource = mock(DataSource.class);
  given(this.dataSource.getConnection()).willThrow(sqlException);
  this.template = new JdbcTemplate();
  this.template.setDataSource(this.dataSource);
  this.template.afterPropertiesSet();
  RowCountCallbackHandler rcch = new RowCountCallbackHandler();
  this.thrown.expect(CannotGetJdbcConnectionException.class);
  this.thrown.expect(exceptionCause(sameInstance(sqlException)));
  this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testSQLErrorCodeTranslationWithSpecifiedDbName() throws Exception {
  final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
  final String sql = "SELECT ID FROM CUSTOMER";
  given(this.resultSet.next()).willReturn(true);
  given(this.connection.createStatement()).willReturn(this.preparedStatement);
  JdbcTemplate template = new JdbcTemplate();
  template.setDataSource(this.dataSource);
  template.setDatabaseProductName("MySQL");
  template.afterPropertiesSet();
  this.thrown.expect(BadSqlGrammarException.class);
  this.thrown.expect(exceptionCause(sameInstance(sqlException)));
  try {
    template.query(sql, (RowCallbackHandler) rs -> {
      throw sqlException;
    });
  }
  finally {
    verify(this.resultSet).close();
    verify(this.preparedStatement).close();
    verify(this.connection).close();
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Before
public void setUp() throws SQLException {
  given(connection.createStatement()).willReturn(statement);
  given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
  given(statement.executeQuery(anyString())).willReturn(resultSet);
  given(preparedStatement.executeQuery()).willReturn(resultSet);
  given(resultSet.next()).willReturn(true, true, false);
  given(resultSet.getString(1)).willReturn("tb1", "tb2");
  given(resultSet.getInt(2)).willReturn(1, 2);
  template.setDataSource(new SingleConnectionDataSource(connection, false));
  template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
  template.afterPropertiesSet();
}

代码示例来源:origin: alibaba/nacos

@PostConstruct
public void init() {
  BasicDataSource ds = new BasicDataSource();
  ds.setDriverClassName(JDBC_DRIVER_NAME);
  ds.setUrl("jdbc:derby:" + NACOS_HOME + File.separator + DERBY_BASE_DIR + ";create=true");
  ds.setUsername(USER_NAME);
  ds.setPassword(PASSWORD);
  ds.setInitialSize(20);
  ds.setMaxActive(30);
  ds.setMaxIdle(50);
  ds.setMaxWait(10000L);
  ds.setPoolPreparedStatements(true);
  ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES
    .toMillis(10L));
  ds.setTestWhileIdle(true);
  jt = new JdbcTemplate();
  jt.setMaxRows(50000);
  jt.setQueryTimeout(5000);
  jt.setDataSource(ds);
  DataSourceTransactionManager tm = new DataSourceTransactionManager();
  tjt = new TransactionTemplate(tm);
  tm.setDataSource(ds);
  tjt.setTimeout(5000);
  if (STANDALONE_MODE && !propertyUtil.isStandaloneUseMysql()) {
    reload();
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Test that we see an SQLException translated using Error Code.
 * If we provide the SQLExceptionTranslator, we shouldn't use a connection
 * to get the metadata
 */
@Test
public void testUseCustomSQLErrorCodeTranslator() throws Exception {
  // Bad SQL state
  final SQLException sqlException = new SQLException("I have a known problem", "07000", 1054);
  final String sql = "SELECT ID FROM CUSTOMER";
  given(this.resultSet.next()).willReturn(true);
  given(this.connection.createStatement()).willReturn(this.preparedStatement);
  JdbcTemplate template = new JdbcTemplate();
  template.setDataSource(this.dataSource);
  // Set custom exception translator
  template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
  template.afterPropertiesSet();
  this.thrown.expect(BadSqlGrammarException.class);
  this.thrown.expect(exceptionCause(sameInstance(sqlException)));
  try {
    template.query(sql, (RowCallbackHandler) rs -> {
      throw sqlException;
    });
  }
  finally {
    verify(this.resultSet).close();
    verify(this.preparedStatement).close();
    verify(this.connection).close();
  }
}

代码示例来源:origin: spring-projects/spring-framework

template.setDataSource(this.dataSource);
if (fetchSize != null) {
  template.setFetchSize(fetchSize.intValue());

代码示例来源:origin: spring-projects/spring-framework

/**
 * If beanProperty is true, initialize via exception translator bean property;
 * if false, use afterPropertiesSet().
 */
private void doTestCouldNotGetConnectionInOperationWithExceptionTranslatorInitialized(boolean beanProperty)
    throws SQLException {
  SQLException sqlException = new SQLException("foo", "07xxx");
  this.dataSource = mock(DataSource.class);
  given(this.dataSource.getConnection()).willThrow(sqlException);
  this.template = new JdbcTemplate();
  this.template.setDataSource(this.dataSource);
  this.template.setLazyInit(false);
  if (beanProperty) {
    // This will get a connection.
    this.template.setExceptionTranslator(new SQLErrorCodeSQLExceptionTranslator(this.dataSource));
  }
  else {
    // This will cause creation of default SQL translator.
    this.template.afterPropertiesSet();
  }
  RowCountCallbackHandler rcch = new RowCountCallbackHandler();
  this.thrown.expect(CannotGetJdbcConnectionException.class);
  this.thrown.expect(exceptionCause(sameInstance(sqlException)));
  this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
  connection = mock(Connection.class);
  statement = mock(Statement.class);
  resultSet = mock(ResultSet.class);
  resultSetMetaData = mock(ResultSetMetaData.class);
  given(connection.createStatement()).willReturn(statement);
  given(statement.executeQuery(anyString())).willReturn(resultSet);
  given(resultSet.getMetaData()).willReturn(resultSetMetaData);
  given(resultSet.next()).willReturn(true, false);
  given(resultSet.getString(1)).willReturn("Bubba");
  given(resultSet.getLong(2)).willReturn(22L);
  given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
  given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
  given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
  given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
  given(resultSet.wasNull()).willReturn(type == MockType.TWO);
  given(resultSetMetaData.getColumnCount()).willReturn(4);
  given(resultSetMetaData.getColumnLabel(1)).willReturn(
      type == MockType.THREE ? "Last Name" : "name");
  given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
  given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
  given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");
  jdbcTemplate = new JdbcTemplate();
  jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
  jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
  jdbcTemplate.afterPropertiesSet();
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Confirm our JdbcTemplate is used
 *
 * @throws Exception
 */
@Test
public void testStoredProcedureConfiguredViaJdbcTemplate() throws Exception {
  given(callableStatement.execute()).willReturn(false);
  given(callableStatement.getUpdateCount()).willReturn(-1);
  given(callableStatement.getObject(2)).willReturn(4);
  given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
      ).willReturn(callableStatement);
  JdbcTemplate t = new JdbcTemplate();
  t.setDataSource(dataSource);
  StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);
  assertEquals(4, sp.execute(1106));
  verify(callableStatement).setObject(1, 1106, Types.INTEGER);
  verify(callableStatement).registerOutParameter(2, Types.INTEGER);
}

代码示例来源:origin: jamesagnew/hapi-fhir

@Nonnull
public JdbcTemplate newJdbcTemplate() {
  JdbcTemplate jdbcTemplate = new JdbcTemplate();
  jdbcTemplate.setDataSource(myDataSource);
  return jdbcTemplate;
}

代码示例来源:origin: lianggzone/springboot-action

@Bean
  public JdbcTemplate jdbcTemplate() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(dataSource());
    return jdbcTemplate;
  }
}

代码示例来源:origin: yandex/graphouse

@Bean
public JdbcTemplate clickHouseJdbcTemplateAutohide(
  DataSource clickHouseDataSource,
  @Value("${graphouse.autohide.clickhouse.query-timeout-seconds}") int autoHideQueryTimeoutSeconds) {
  final JdbcTemplate jdbcTemplate = new JdbcTemplate();
  jdbcTemplate.setDataSource(clickHouseDataSource);
  jdbcTemplate.setQueryTimeout(autoHideQueryTimeoutSeconds);
  return jdbcTemplate;
}

相关文章