spring JdbcTemplate批量插入 怎么获得数据库自动增长的id

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring JdbcTemplate批量插入 怎么获得数据库自动增长的id相关的知识,希望对你有一定的参考价值。

参考技术A spring
JdbcTemplate批量例子:
@Override
public
void
saveBatch(final
List<Employee>
employeeList)

final
int
batchSize
=
500;
for
(int
j
=
0;
j
<
employeeList.size();
j
+=
batchSize)

final
List<Employee>
batchList
=
employeeList.subList(j,
j
+
batchSize
>
employeeList.size()
?
employeeList.size()
:
j
+
batchSize);
getJdbcTemplate().batchUpdate(QUERY_SAVE,
new
BatchPreparedStatementSetter()

@Override
public
void
setValues(PreparedStatement
ps,
int
i)
throws
SQLException

Employee
employee
=
batchList.get(i);
ps.setString(1,
employee.getFirstname());
ps.setString(2,
employee.getLastname());
ps.setString(3,
employee.getEmployeeIdOnSourceSystem());

@Override
public
int
getBatchSize()

return
batchList.size();

);


主键自动增加可以在db层面建立sequence来实现,在插入的时候这么写:
Long
newPersonId
=
holder.getKey().longValue();

Spring二刷笔记-JdbcTemplate

一、使用JdbcTemplate依赖

spring-jdbc:spring自带封装的jdbc
spring-tx:事务依赖Tranaction
spring-orm:spring整合数据层框架所需依赖

		<!--mysql连接驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <!--spring自己封装的jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.6</version>
        </dependency>


        <!--事务依赖 Transaction -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!--spring整合数据层框架所需依赖-->
        <dependency>
            <groupId>springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>1.2.6</version>
        </dependency>

以下样例使用的druid连接池

	<!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>

二、配置Druid数据源和JdbcTemplate

	<!--引入外部文件-->
	<context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

三、JdbcTemplate操作数据库

1、样例代码

(1)dao层

给dao层实现类注入jdbcTemplate
使用jdbcTemplate实现CRUD

@Repository
public class TicketMapper implements TicketDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
	//添加数据
    public void add(Ticket ticket) {
        String sql="insert into ticket (id,name,author) values(?,?,?)";
        int update=jdbcTemplate.update(sql,ticket.getTicketId(),ticket.getTicketName(),ticket.getAuthor());
        System.out.println(update);
    }
	//删除数据
    public void delete(int id) {
        String sql="delete from ticket where id=?";
        int update=jdbcTemplate.update(sql,id);
        System.out.println(update);
    }

    //查询对象
    public Ticket query(int id) {
        String sql="select id ticketId,name ticketName,author from ticket where id=?";
        Ticket ticket=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Ticket>(Ticket.class),id);
        return ticket;
    }
	//查询集合
    public List<Ticket> findAll() {
        String sql="select id ticketId,name ticketName,author from ticket";
        List<Ticket> ticketList=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Ticket>(Ticket.class));
        return ticketList;
    }

    public void update(Ticket ticket) {
        String sql="update ticket set name=? , author=? where id=?";
        String args[]={ticket.getTicketName(),ticket.getAuthor(),ticket.getTicketId()};

        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);

    }
    //查询记录总数
    public int seleteCount() {
        String sql="select COUNT(*) from ticket";
        Integer cnt = jdbcTemplate.queryForObject(sql, Integer.class);
        return cnt;
    }
    //批量添加
    public void batchAdd(List<Object[]> batchList) {
        String sql="insert into ticket (id,name,author) values(?,?,?)";
        //批量添加 values (),(),()  对象这list的Object数组 o1,o2,o3
        int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
        System.out.println(Arrays.toString(ints));
    }
    //批量删除
    public void batchDelete(List<Object[]> batchList) {
        String sql="delete from ticket where id=?";
        int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
        System.out.println(Arrays.toString(ints));
    }
    //批量修改
    public void batchUpdate(List<Object[]> batchList) {
        String sql="update ticket set name=?,author=? where id=?";
        int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
        System.out.println(Arrays.toString(ints));
    }
}

(2)service层

给Service实现类注入dao,使用dao来完成操作

@Service("ticketService")
public class TicketServiceImpl implements TicketService{
    @Autowired
    TicketDao ticketDao;

    public void add(Ticket ticket) {
        ticketDao.add(ticket);
    }

    public void delete(int id) {
        ticketDao.delete(id);
    }

    public Ticket query(int id) {
        return ticketDao.query(id);
    }

    public List<Ticket> findAll() {
        return ticketDao.findAll();
    }

    public void update(Ticket ticket) {
        ticketDao.update(ticket);
    }

    public int getCount() {
        return ticketDao.seleteCount();
    }
    public void batchAdd(List<Object[]> batchList) {
        ticketDao.batchAdd(batchList);
    }

    public void batchDelete(List<Object[]> batchList) {
        ticketDao.batchDelete(batchList);
    }

    public void batchUpdate(List<Object[]> batchList) {
        ticketDao.batchUpdate(batchList);
    }
}

2、不同查询

(1)普通查询

					jdbcTemplate.queryForObject(
									sql,
									Integer.class   //返回什么类型写什么
					);

(2)对象查询

 jdbcTemplate.queryForObject(
		sql,      //sql语句
		new BeanPropertyRowMapper<Ticket>(Ticket.class),  //RowMapper 查询的什么类型泛型写什么
		id        //sql参数
);

(3)集合查询

应用场景:查询分页

		jdbcTemplate.query(
							sql,      //sql语句
							new BeanPropertyRowMapper<Ticket>(Ticket.class)
		);		
 //查询对象
    public Ticket query(int id) {
        String sql="select id ticketId,name ticketName,author from ticket where id=?";
        Ticket ticket=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Ticket>(Ticket.class),id);
        return ticket;
    }
	//查询集合
    public List<Ticket> findAll() {
        String sql="select id ticketId,name ticketName,author from ticket";
        List<Ticket> ticketList=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Ticket>(Ticket.class));
        return ticketList;
    }
ApplicationContext context=new ClassPathXmlApplicationContext("bean2.xml");

        Ticket ticket=new Ticket("3","砍僵尸","林正英");
        TicketService ticketService = context.getBean("ticketService", TicketService.class);
        int id=5;
        Ticket ticket=ticketService.query(id);

java.lang.NoSuchMethodException
这个错误发现是实体类没有无参构造,无法映射

3.批量操作

(1)批量添加

//批量添加
   public void batchAdd(List<Object[]> batchList) {
       String sql="insert into ticket (id,name,author) values(?,?,?)";
       //批量添加 values (),(),()  对象这list的Object数组 o1,o2,o3
       int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
       System.out.println(Arrays.toString(ints));
   }
	 List<Object[]> batchList=new ArrayList<Object[]>();
       Object[] o1={"5","Web"};
       Object[] o2={"6","大数据","2"};
       Object[] o3={"7","中间件","3"}; 
       batchList.add(o1);
       batchList.add(o2);
       batchList.add(o3);
       ticketService.batchAdd(batchList);

(2)批量删除

 //批量删除
 public void batchDelete(List<Object[]> batchList) {
     String sql="delete from ticket where id=?";
     int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
     System.out.println(Arrays.toString(ints));
 }

(3)批量修改

   //批量修改
   public void batchUpdate(List<Object[]> batchList) {
       String sql="update ticket set name=?,author=? where id=?";
       int[] ints=jdbcTemplate.batchUpdate(sql,batchList);
       System.out.println(Arrays.toString(ints));
   }

以上是关于spring JdbcTemplate批量插入 怎么获得数据库自动增长的id的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Spring 的 jdbcTemplate.batchUpdate() 这么慢?

JdbcTemplate数据批量删除

Spring JdbcTemplate batchUpdate() 实例

Spring入门后半部分----JDBCTemplate和事务控制

使用 jdbcTemplate.batchUpdate 混淆批量插入

Spring二刷笔记-JdbcTemplate