DataSourceUtils.getConnection(jdbcTemplate.getDataSource())。commit();无法运作,即无法提交

时间:2019-06-10 09:32:15

标签: java spring-jdbc jdbctemplate

我是JDBC模板的新手,并且正在尝试使用准备好的语句通过自动提交模式关闭将数据插入数据库中以实现高性能,但最后我无法提交事务。请提出一些可能解决我问题的正确方法或参考。

预先感谢...

SpringjdbcApplication.java

@SpringBootApplication
public class SpringjdbcApplication 
{
    public static void main(String[] args) 
    {
        ApplicationContext context  = SpringApplication.run(SpringjdbcApplication.class, args);
        SampleService service = context.getBean(SampleService.class);

        List<Batch> batchList = new ArrayList<>();
        batchList.add(new Batch("A","B"));
        batchList.add(new Batch("B","B"));
        batchList.add(new Batch("C","B"));
        batchList.add(new Batch("D","B"));
        batchList.add(new Batch("E","B"));
        System.err.println("The number of rows inserted = "+service.singleInsert(batchList));
        System.err.println("The count of batch class is = "+service.getCount());
    }

}

SampleConfiguration.java

@Configuration
public class SampleConfiguration 
{
    @Bean
    public DataSource mysqlDataSource() 
    {
        HikariConfig config= new HikariConfig();
        config.setDriverClassName("ClassName");
        config.setJdbcUrl("URL");
        config.setUsername("User");
        config.setPassword("Password");
        config.setMinimumIdle(600);
        config.setMaximumPoolSize(30);
        config.setConnectionTimeout(251);
        config.setMaxLifetime(250);
        config.setAutoCommit(false);
        return new HikariDataSource(config);
    }

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

}

Batch.java

@Entity
public class Batch implements Serializable 
{

    private static final long serialVersionUID = -5687736664713755991L;

    @Id
    @Column(name="field1")
    private String field1;

    @Column(name="field2")
    private String field2;

        ....... getter, setter and constructor
}

SampleService.java

@Service
public interface SampleService 
{
    public int singleInsert(List<Batch> batchList);
}

SampleServiceImpl.java

@Service
public class SampleServiceImpl implements SampleService 
{

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public int singleInsert(List<Batch> batchList) 
    {
        for(Batch i:batchList)
        {
            jdbcTemplate.update("insert into batch values(?,?)",i.getField1(),i.getField2());
        }

        try
        {
            DataSourceUtils.getConnection(jdbcTemplate.getDataSource()).commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return 1;
    }

}

0 个答案:

没有答案