dao接口:
package com.wzy.jdbctemplate.dao;import com.wzy.jdbctemplate.pojo.Book;import java.util.List;public interface BookDao {void addBookAllDaoImpl(List<Object[]> list);}
dao接口实现类:
package com.wzy.jdbctemplate.dao.impl;import com.wzy.jdbctemplate.dao.BookDao;import com.wzy.jdbctemplate.pojo.Book;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;import java.util.Arrays;import java.util.List;@Repository//创建对象public class BookDaoImpl implements BookDao {@Autowired//自动装配JdbcTemplate jdbcTemplate;@Overridepublic void addBookAllDaoImpl(List<Object[]> list) {String sql = "insert into book values (?,?,?,?)";int[] ints = jdbcTemplate.batchUpdate(sql, list);System.out.println(Arrays.toString(ints));}}
service类:
package com.wzy.jdbctemplate.service;import com.wzy.jdbctemplate.dao.BookDao;import com.wzy.jdbctemplate.pojo.Book;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Service//创建对象public class BookService {@Autowired//自动装配private BookDao bookDao;//批量插入public void addBookAllSer(List<Object[]> list){bookDao.addBookAllDaoImpl(list);}}
测试类:
package com.wzy.jdbctemplate.test;import com.wzy.jdbctemplate.pojo.Book;import com.wzy.jdbctemplate.service.BookService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.ArrayList;import java.util.Collections;import java.util.List;import static org.junit.Assert.*;public class BookServiceTest {ApplicationContext applicationContext =new ClassPathXmlApplicationContext("com/wzy/jdbctemplate/spring.xml");BookService bookService = applicationContext.getBean("bookService",BookService.class);@Testpublic void addBookAllSer(){List<Object[]> list = new ArrayList<>();Object[] o1 = {"7","java","a","qqeqw@163.om"};Object[] o2 = {"8","c++","b","wwewe@163.om"};Object[] o3 = {"9","MySQL","c","fewgr@163.om"};Collections.addAll(list,o1,o2,o3);bookService.addBookAllSer(list);}}
