Spring教程
作者: 时海 hadoop迷
批量插入

Spring JdbcTemplate批量插入:

package spring.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        createTestData(jdbcTemplate);
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        User user = jdbcTemplate.queryForObject("select * from user where id=?", rowMapper, new Object[]{1});
        System.out.println(user);
    }

    static void createTestData(JdbcTemplate jdbcTemplate) {
        jdbcTemplate.execute("create table if not exists user(id int primary key,name varchar(10),age int)");
        List<Object[]> dataList = new ArrayList<>();
        dataList.add(new Object[]{1, "zhansan", 30});
        dataList.add(new Object[]{2, "lisi", 40});
        dataList.add(new Object[]{3, "wangwu", 50});
        int[] returnCodes = jdbcTemplate.batchUpdate("insert into  user values(?,?,?)", dataList);
        System.out.println(Arrays.toString(returnCodes));
        //output: [1, 1, 1]
    }
}


一个创业中的苦逼程序员
  • 回复
隐藏