jdbcTemplate.batchUpdate不插入行

时间:2018-11-18 17:37:29

标签: java jdbctemplate

我正在尝试进行批处理插入,但是在Tomcat中运行时,该应用程序似乎挂起,没有插入新行。下面是我的代码:

public class MatchDAOImpl implements MatchDAO {

    private JdbcTemplate jdbcTemplate;

    public MatchDAOImpl(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void batchInsert(final List<Match> matches){

        String sql = "INSERT INTO matches (id, status, home_team_id, away_team_id, home_goals, away_goals) VALUES (?, ?, ?, ?, ?, ?)";

        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                Match match = matches.get(i);
                System.out.println("Inserting values for #" + match.getId());
                ps.setInt(1, match.getId());
                ps.setString(2, match.getStatus());
                ps.setInt(3, match.getHomeTeam().getId());
                ps.setInt(4, match.getAwayTeam().getId());
                ps.setInt(5, match.getHomeGoals());
                ps.setInt(6, match.getAwayGoals());
            }

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

以下是被称为的示例:

matchesDAO.batchInsert(matches);

此外,您还会看到我有一个println命令,因此我知道它至少正在使用此方法。以下是此示例输出:

Inserting values for #233398
Inserting values for #233399
Inserting values for #233400
Inserting values for #233401
Inserting values for #233402
...

但是,当我检查数据库中是否有任何新行时(空表)却没有。我没有抛出任何异常来表明问题所在。我的方法看起来还可以吗?

更新

MvcConfig.java

@Configuration
@ComponentScan(basePackages="com.example.budget")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

    //...

    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
//      dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        dataSource.setDriverClassName( OracleDriver.class.getName() );
        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
        dataSource.setUsername("budget_admin");
        dataSource.setPassword("budg3t");

        return dataSource;
    }

    @Bean
    public MatchDAO getMatchDAO() {
        return new MatchDAOImpl(getDataSource());
    }

这是现在正在调用batchInsert的地方:

@Controller
public class MatchesController {

    @Autowired
    private FootballData footballData;

    @Autowired 
    private MatchDAO matchDAOImpl;

    @RequestMapping(value = "/api/matches")
    public ModelAndView matches(ModelAndView model) {

        List<Match> matches = footballData.requestMatches();

        // write to db
        matchDAOImpl.batchInsert(matches);

        model.addObject("matches", matches);
        model.setViewName("matches");

        return model;
    }

0 个答案:

没有答案