예제 #1
0
 @Bean
 public DataSource dataSource() throws SQLException {
   SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
   dataSource.setDriver(new Driver());
   dataSource.setUrl("jdbc:mysql://localhost:3306/pensiondb");
   dataSource.setUsername("root");
   dataSource.setPassword("teresa");
   return dataSource;
 }
  private static void persistProductList(final List<Product> products) {
    try {
      SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
      dataSource.setDriver(new com.mysql.jdbc.Driver());
      dataSource.setUrl("jdbc:mysql://localhost/inventory");
      dataSource.setUsername("root");
      // dataSource.setPassword("P@ssw0rd");
      JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
      String sql =
          "insert into products (productName, productCode, productType, sellingRate, costRate, createdDate, updatedDate) values ( ?, ?, ?, ?, ?, ?, ?)";

      jdbcTemplate.batchUpdate(
          sql,
          new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
              Product product = products.get(i);
              preparedStatement.setString(1, product.getProductName());
              preparedStatement.setString(2, product.getProductCode());
              preparedStatement.setString(3, product.getProductType());
              preparedStatement.setDouble(
                  4, (product.getSellingRate() == null ? 0 : product.getSellingRate()));
              preparedStatement.setDouble(
                  5, (product.getCostRate() == null ? 0 : product.getCostRate()));
              preparedStatement.setDate(6, new Date((new java.util.Date()).getTime()));
              preparedStatement.setDate(7, new Date((new java.util.Date()).getTime()));
            }

            @Override
            public int getBatchSize() {
              return products.size();
            }
          });

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }