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

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

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

JdbcTemplate.afterPropertiesSet介绍

暂无

代码示例

代码示例来源: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-session

private static JdbcTemplate createJdbcTemplate(DataSource dataSource) {
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  jdbcTemplate.afterPropertiesSet();
  return jdbcTemplate;
}

代码示例来源: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: spring-projects/spring-framework

/**
 * Compile this query.
 * Ignores subsequent attempts to compile.
 * @throws InvalidDataAccessApiUsageException if the object hasn't
 * been correctly initialized, for example if no DataSource has been provided
 */
public final void compile() throws InvalidDataAccessApiUsageException {
  if (!isCompiled()) {
    if (getSql() == null) {
      throw new InvalidDataAccessApiUsageException("Property 'sql' is required");
    }
    try {
      this.jdbcTemplate.afterPropertiesSet();
    }
    catch (IllegalArgumentException ex) {
      throw new InvalidDataAccessApiUsageException(ex.getMessage());
    }
    compileInternal();
    this.compiled = true;
    if (logger.isDebugEnabled()) {
      logger.debug("RdbmsOperation with SQL [" + getSql() + "] compiled");
    }
  }
}

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

/**
 * Compile this JdbcInsert using provided parameters and meta-data plus other settings.
 * This finalizes the configuration for this object and subsequent attempts to compile are
 * ignored. This will be implicitly called the first time an un-compiled insert is executed.
 * @throws InvalidDataAccessApiUsageException if the object hasn't been correctly initialized,
 * for example if no DataSource has been provided
 */
public final synchronized void compile() throws InvalidDataAccessApiUsageException {
  if (!isCompiled()) {
    if (getTableName() == null) {
      throw new InvalidDataAccessApiUsageException("Table name is required");
    }
    try {
      this.jdbcTemplate.afterPropertiesSet();
    }
    catch (IllegalArgumentException ex) {
      throw new InvalidDataAccessApiUsageException(ex.getMessage());
    }
    compileInternal();
    this.compiled = true;
    if (logger.isDebugEnabled()) {
      logger.debug("JdbcInsert for table [" + getTableName() + "] compiled");
    }
  }
}

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

/**
 * Compile this JdbcCall using provided parameters and meta-data plus other settings.
 * <p>This finalizes the configuration for this object and subsequent attempts to compile are
 * ignored. This will be implicitly called the first time an un-compiled call is executed.
 * @throws org.springframework.dao.InvalidDataAccessApiUsageException if the object hasn't
 * been correctly initialized, for example if no DataSource has been provided
 */
public final synchronized void compile() throws InvalidDataAccessApiUsageException {
  if (!isCompiled()) {
    if (getProcedureName() == null) {
      throw new InvalidDataAccessApiUsageException("Procedure or Function name is required");
    }
    try {
      this.jdbcTemplate.afterPropertiesSet();
    }
    catch (IllegalArgumentException ex) {
      throw new InvalidDataAccessApiUsageException(ex.getMessage());
    }
    compileInternal();
    this.compiled = true;
    if (logger.isDebugEnabled()) {
      logger.debug("SqlCall for " + (isFunction() ? "function" : "procedure") +
          " [" + getProcedureName() + "] compiled");
    }
  }
}

代码示例来源: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: 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

/**
 * 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-integration

/**
 * Check mandatory properties ({@link DataSource} and
 * {@link #setChannelMessageStoreQueryProvider(ChannelMessageStoreQueryProvider)}). If no {@link MessageRowMapper}
 * and {@link ChannelMessageStorePreparedStatementSetter} was explicitly set using
 * {@link #setMessageRowMapper(MessageRowMapper)} and
 * {@link #setPreparedStatementSetter(ChannelMessageStorePreparedStatementSetter)}  respectively, the default
 * {@link MessageRowMapper} and {@link ChannelMessageStorePreparedStatementSetter} will be instantiate using the
 * specified {@link #deserializer} and {@link #lobHandler}.
 * Also, if the jdbcTemplate's fetchSize property ({@link JdbcTemplate#getFetchSize()})
 * is not 1, a warning will be logged. When using the {@link JdbcChannelMessageStore}
 * with Oracle, the fetchSize value of 1 is needed to ensure FIFO characteristics
 * of polled messages. Please see the Oracle {@link ChannelMessageStoreQueryProvider} for more details.
 * @throws Exception Any Exception.
 */
@Override
public void afterPropertiesSet() throws Exception {
  Assert.state(this.jdbcTemplate != null, "A DataSource or JdbcTemplate must be provided");
  Assert.notNull(this.channelMessageStoreQueryProvider, "A channelMessageStoreQueryProvider must be provided.");
  if (this.messageRowMapper == null) {
    this.messageRowMapper = new MessageRowMapper(this.deserializer, this.lobHandler);
  }
  if (this.jdbcTemplate.getFetchSize() != 1 && logger.isWarnEnabled()) {
    logger.warn("The jdbcTemplate's fetch size is not 1. This may cause FIFO issues with Oracle databases.");
  }
  if (this.preparedStatementSetter == null) {
    this.preparedStatementSetter = new ChannelMessageStorePreparedStatementSetter(this.serializer,
        this.lobHandler);
  }
  this.jdbcTemplate.afterPropertiesSet();
}

代码示例来源:origin: io.bufferslayer/buffer-spring-jdbc

public void afterPropertiesSet() {
  delegate.afterPropertiesSet();
 }
}

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

@Test
@Transactional
public void testRemoveMessageGroup() throws Exception {
  JdbcTemplate template = new JdbcTemplate(dataSource);
  template.afterPropertiesSet();
  String groupId = "X";
  Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(groupId).build();
  messageStore.addMessageToGroup(groupId, message);
  messageStore.removeMessageGroup(groupId);
  MessageGroup group = messageStore.getMessageGroup(groupId);
  assertEquals(0, group.size());
  String uuidGroupId = UUIDConverter.getUUID(groupId).toString();
  assertTrue(template.queryForList(
      "SELECT * from INT_GROUP_TO_MESSAGE where GROUP_KEY = '" + uuidGroupId + "'").size() == 0);
}

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

@Test
public void testRemoveMessageGroup() throws Exception {
  JdbcTemplate template = new JdbcTemplate(this.dataSource);
  template.afterPropertiesSet();
  String groupId = "X";
  Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(groupId).build();
  messageStore.addMessagesToGroup(groupId, message);
  messageStore.removeMessageGroup(groupId);
  MessageGroup group = messageStore.getMessageGroup(groupId);
  assertEquals(0, group.size());
  String uuidGroupId = UUIDConverter.getUUID(groupId).toString();
  assertTrue(template.queryForList(
      "SELECT * from INT_GROUP_TO_MESSAGE where GROUP_KEY = ?", uuidGroupId).size() == 0);
}

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

@Test
public void testExpireMessageGroupOnCreateOnly() throws Exception {
  final String groupId = "X";
  Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(groupId).build();
  messageStore.addMessagesToGroup(groupId, message);
  final CountDownLatch groupRemovalLatch = new CountDownLatch(1);
  messageStore.registerMessageGroupExpiryCallback((messageGroupStore, group) -> {
    messageGroupStore.removeMessageGroup(group.getGroupId());
    groupRemovalLatch.countDown();
  });
  messageStore.expireMessageGroups(2000);
  MessageGroup group = messageStore.getMessageGroup(groupId);
  assertEquals(1, group.size());
  messageStore.addMessagesToGroup(groupId, MessageBuilder.withPayload("bar").setCorrelationId(groupId).build());
  JdbcTemplate template = new JdbcTemplate(this.dataSource);
  template.afterPropertiesSet();
  template.update("UPDATE INT_MESSAGE_GROUP set CREATED_DATE=? where GROUP_KEY=? and REGION=?",
      (PreparedStatementSetter) ps -> {
        ps.setTimestamp(1, new Timestamp(System.currentTimeMillis() - 10000));
        ps.setString(2, UUIDConverter.getUUID(groupId).toString());
        ps.setString(3, "DEFAULT");
      });
  messageStore.expireMessageGroups(2000);
  group = messageStore.getMessageGroup(groupId);
  assertEquals(0, group.size());
  assertTrue(groupRemovalLatch.await(10, TimeUnit.SECONDS));
}

代码示例来源:origin: org.springframework/org.springframework.jdbc

/**
 * 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: apache/servicemix-bundles

/**
 * 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: spring-projects/spring-integration

@Test
public void testExpireMessageGroupOnIdleOnly() throws Exception {
  String groupId = "X";
  Message<String> message = MessageBuilder.withPayload("foo").setCorrelationId(groupId).build();
  messageStore.setTimeoutOnIdle(true);
  messageStore.addMessagesToGroup(groupId, message);
  messageStore.registerMessageGroupExpiryCallback((messageGroupStore, group) -> messageGroupStore.removeMessageGroup(group.getGroupId()));
  JdbcTemplate template = new JdbcTemplate(this.dataSource);
  template.afterPropertiesSet();
  updateMessageGroup(template, groupId, 1000);
  messageStore.expireMessageGroups(2000);
  MessageGroup group = messageStore.getMessageGroup(groupId);
  assertEquals(1, group.size());
  updateMessageGroup(template, groupId, 2000);
  messageStore.addMessagesToGroup(groupId, MessageBuilder.withPayload("bar").setCorrelationId(groupId).build());
  group = messageStore.getMessageGroup(groupId);
  assertEquals(2, group.size());
  updateMessageGroup(template, groupId, 2000);
  messageStore.expireMessageGroups(2000);
  group = messageStore.getMessageGroup(groupId);
  assertEquals(0, group.size());
}

相关文章