spring4 -- JdbcTemplate数据库操作

spring和数据库的交互主要由jdbcTemplate完成。
要和数据库交互,在主配置文件里加入dataSource配置后,还需要在Dao层完成数据源的注入:

private JdbcTemplate sjc; @Autowired public void setDataSource(DataSource dataSource) { this.sjc = new JdbcTemplate(dataSource); }

之后对数据库的操作就变得很简单:
查询:

public String getName() { return this.jdbcTemplate.queryForObject("select name from mytable where id = 1", String.class); }

对于只有一条记录的查询可以将结果直接封装给特定对象,这样就大大简化了数据库操作代码。

public List<Map<String, Object>> getList() { return this.jdbcTemplate.queryForList("select * from mytable"); }

对于多条结果集的,可以直接将其封装到list中。

更新操作:

public void setName(int id, String name) { this.jdbcTemplate.update("update mytable set name = ? where id = ?", name, id); }


批量更新,batchUpdate主要有两个参数,一个是sql,另一个是参数设置类 BatchPreparedStatementSetter,getBatchSize会获取到需要批量处理的数量,然后在setValue中设置相应参数

public int[] batchUpdate(final List<Actor> actors) { int[] updateCounts = jdbcTemplate.batchUpdate("update t_actor set first_name = ?, " + "last_name = ? where id = ?", new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setString(1, actors.get(i).getFirstName()); ps.setString(2, actors.get(i).getLastName()); ps.setLong(3, actors.get(i).getId().longValue()); } public int getBatchSize() { return actors.size(); } }); return updateCounts; }

另一种处理方式:

public int[] batchUpdate(final List<Actor> actors) { List<Object[]> batch = new ArrayList<Object[]>(); for (Actor actor : actors) { Object[] values = new Object[] { actor.getFirstName(), actor.getLastName(), actor.getId()}; batch.add(values); } int[] updateCounts = jdbcTemplate.batchUpdate( "update t_actor set first_name = ?, last_name = ? where id = ?", batch); return updateCounts; }

对于大批量操作,可将其切分成一个一个小段来进行批量操作,下面的就是按每100个进行一次数据库交互来实现:

public int[][] batchUpdate(final Collection<Actor> actors) { int[][] updateCounts = jdbcTemplate.batchUpdate( "update t_actor set first_name = ?, last_name = ? where id = ?", actors, 100, new ParameterizedPreparedStatementSetter<Actor>() { public void setValues(PreparedStatement ps, Actor argument) throws SQLException{ ps.setString(1, argument.getFirstName()); ps.setString(2, argument.getLastName()); ps.setLong(3, argument.getId().longValue()); } }); return updateCounts; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值