org.springframework.jdbc.core.JdbcTemplate类的使用及代码示例

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

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

JdbcTemplate介绍

[英]This is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative exception hierarchy defined in the org.springframework.dao package.

Code using this class need only implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection, providing SQL and any necessary parameters. The ResultSetExtractor interface extracts values from a ResultSet. See also PreparedStatementSetter and RowMapper for two popular alternative callback interfaces.

Can be used within a service implementation via direct instantiation with a DataSource reference, or get prepared in an application context and given to services as bean reference. Note: The DataSource should always be configured as a bean in the application context, in the first case given to the service directly, in the second case to the prepared template.

Because this class is parameterizable by the callback interfaces and the org.springframework.jdbc.support.SQLExceptionTranslatorinterface, there should be no need to subclass it.

All SQL operations performed by this class are logged at debug level, using "org.springframework.jdbc.core.JdbcTemplate" as log category.

NOTE: An instance of this class is thread-safe once configured.
[中]这是JDBC核心包中的中心类。它简化了JDBC的使用,并有助于避免常见错误。它执行核心JDBC工作流,让应用程序代码提供SQL和提取结果。这个类执行SQL查询或更新,在结果集上启动迭代,捕获JDBC异常,并将它们转换为组织中定义的通用的、信息更丰富的异常层次结构。springframework。dao包。
使用这个类的代码只需要实现回调接口,给它们一个明确定义的契约。PreparedStatementCreator回调接口在给定连接的情况下创建一个prepared语句,提供SQL和任何必要的参数。ResultSetTextRactor接口从ResultSet中提取值。另请参见PreparedStatementSetter和RowMapper,了解两个流行的可选回调接口。
可以通过数据源引用直接实例化在服务实现中使用,也可以在应用程序上下文中准备并作为bean引用提供给服务。注意:数据源应始终在应用程序上下文中配置为bean,在第一种情况下直接提供给服务,在第二种情况下提供给准备好的模板。
因为这个类可以通过回调接口和组织参数化。springframework。jdbc。支持SQLExceptionTranslatorinterface,应该不需要对其进行子类化。
此类执行的所有SQL操作都在调试级别记录,使用“org.springframework.jdbc.core.JdbcTemplate”作为日志类别。
注意:此类的实例在配置后是线程安全的。

代码示例

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

/**
 * Create a JdbcTemplate for the given DataSource.
 * Only invoked if populating the DAO with a DataSource reference!
 * <p>Can be overridden in subclasses to provide a JdbcTemplate instance
 * with different configuration, or a custom JdbcTemplate subclass.
 * @param dataSource the JDBC DataSource to create a JdbcTemplate for
 * @return the new JdbcTemplate instance
 * @see #setDataSource
 */
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
  return new JdbcTemplate(dataSource);
}

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

@Override
public int update(PreparedStatementCreator psc) throws DataAccessException {
  return update(psc, (PreparedStatementSetter) null);
}

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

@Override
@Nullable
public <T> T query(PreparedStatementCreator psc, ResultSetExtractor<T> rse) throws DataAccessException {
  return query(psc, null, rse);
}

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

@Override
public int update(String sql, Object[] args, int[] argTypes) throws DataAccessException {
  return update(sql, newArgTypePreparedStatementSetter(args, argTypes));
}

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

@Override
@Nullable
public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {
  return queryForObject(sql, getSingleColumnRowMapper(requiredType));
}

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

@Override
@Nullable
public <T> T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor<T> rse) throws DataAccessException {
  return query(sql, newArgTypePreparedStatementSetter(args, argTypes), rse);
}

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

/**
 * Count the rows in the given table.
 * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
 * @param tableName name of the table to count rows in
 * @return the number of rows in the table
 */
public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName) {
  Integer result = jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.class);
  return (result != null ? result : 0);
}

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

@Test
public void testScriptNameWithPattern() throws Exception {
  context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-pattern-config.xml");
  DataSource dataSource = context.getBean("dataSource", DataSource.class);
  assertCorrectSetup(dataSource);
  JdbcTemplate t = new JdbcTemplate(dataSource);
  assertEquals("Dave", t.queryForObject("select name from T_TEST", String.class));
}

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

@Test
public void testPreparedStatementSetterSucceeds() throws Exception {
  final String sql = "UPDATE FOO SET NAME=? WHERE ID = 1";
  final String name = "Gary";
  int expectedRowsUpdated = 1;
  given(this.preparedStatement.executeUpdate()).willReturn(expectedRowsUpdated);
  PreparedStatementSetter pss = ps -> ps.setString(1, name);
  int actualRowsUpdated = new JdbcTemplate(this.dataSource).update(sql, pss);
  assertEquals("updated correct # of rows", actualRowsUpdated, expectedRowsUpdated);
  verify(this.preparedStatement).setString(1, name);
  verify(this.preparedStatement).close();
  verify(this.connection).close();
}

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

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

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

public List<String> getTenantIdList(int page, int pageSize) {
  String sql = "SELECT tenant_id FROM config_info WHERE tenant_id != '' GROUP BY tenant_id LIMIT ?, ?";
  int from = (page - 1) * pageSize;
  return jt.queryForList(sql, String.class, from, pageSize);
}

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

/**
 * SPR-6038: detect HSQL and stop illegal locks being taken.
 * TODO: Against Quartz 2.2, this test's job doesn't actually execute anymore...
 */
@Test
public void schedulerWithHsqlDataSource() throws Exception {
  // Assume.group(TestGroup.PERFORMANCE);
  DummyJob.param = 0;
  DummyJob.count = 0;
  ClassPathXmlApplicationContext ctx = context("databasePersistence.xml");
  JdbcTemplate jdbcTemplate = new JdbcTemplate(ctx.getBean(DataSource.class));
  assertFalse("No triggers were persisted", jdbcTemplate.queryForList("SELECT * FROM qrtz_triggers").isEmpty());
  /*
  Thread.sleep(3000);
  try {
    assertTrue("DummyJob should have been executed at least once.", DummyJob.count > 0);
  }
  finally {
    ctx.close();
  }
  */
}

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

@Test
public void testBatchUpdateWithEmptyList() throws Exception {
  final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
  JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
  int[] actualRowsAffected = template.batchUpdate(sql, Collections.emptyList());
  assertTrue("executed 0 updates", actualRowsAffected.length == 0);
}

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

@Override
public int update(String sql, @Nullable Object... args) throws DataAccessException {
  return update(sql, newArgPreparedStatementSetter(args));
}

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

/**
 * Drop the specified tables.
 * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
 * @param tableNames the names of the tables to drop
 */
public static void dropTables(JdbcTemplate jdbcTemplate, String... tableNames) {
  for (String tableName : tableNames) {
    jdbcTemplate.execute("DROP TABLE " + tableName);
    if (logger.isInfoEnabled()) {
      logger.info("Dropped table " + tableName);
    }
  }
}

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

@Override
public int update(final String sql) throws DataAccessException {
  Assert.notNull(sql, "SQL must not be null");
  if (logger.isDebugEnabled()) {
    logger.debug("Executing SQL update [" + sql + "]");
  }
  /**
   * Callback to execute the update statement.
   */
  class UpdateStatementCallback implements StatementCallback<Integer>, SqlProvider {
    @Override
    public Integer doInStatement(Statement stmt) throws SQLException {
      int rows = stmt.executeUpdate(sql);
      if (logger.isTraceEnabled()) {
        logger.trace("SQL update affected " + rows + " rows");
      }
      return rows;
    }
    @Override
    public String getSql() {
      return sql;
    }
  }
  return updateCount(execute(new UpdateStatementCallback()));
}

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

@Override
public int update(final PreparedStatementCreator psc, final KeyHolder generatedKeyHolder)
    throws DataAccessException {
  Assert.notNull(generatedKeyHolder, "KeyHolder must not be null");
  logger.debug("Executing SQL update and returning generated keys");
  return updateCount(execute(psc, ps -> {
    int rows = ps.executeUpdate();
    List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
    generatedKeys.clear();
    ResultSet keys = ps.getGeneratedKeys();
    if (keys != null) {
      try {
        RowMapperResultSetExtractor<Map<String, Object>> rse =
            new RowMapperResultSetExtractor<>(getColumnMapRowMapper(), 1);
        generatedKeys.addAll(result(rse.extractData(keys)));
      }
      finally {
        JdbcUtils.closeResultSet(keys);
      }
    }
    if (logger.isTraceEnabled()) {
      logger.trace("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
    }
    return rows;
  }));
}

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

void assertUsersDatabaseCreated(String... lastNames) {
  for (String lastName : lastNames) {
    assertThat("Did not find user with last name [" + lastName + "].",
      jdbcTemplate.queryForObject("select count(0) from users where last_name = ?", Integer.class, lastName),
      equalTo(1));
  }
}

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

@Test
public void testFactoryBeanLifecycle() throws Exception {
  EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
  ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"),
    resource("db-test-data.sql"));
  bean.setDatabasePopulator(populator);
  bean.afterPropertiesSet();
  DataSource ds = bean.getObject();
  JdbcTemplate template = new JdbcTemplate(ds);
  assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class));
  bean.destroy();
}

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

@Override
  public void afterPropertiesSet() throws Exception {
    cache = jdbcTemplate.queryForList("SELECT * FROM T_TEST");
  }
}

相关文章