因为原生的jdbc操作太复杂,几乎都是建立连接、关闭连接和处理例外等模板式的代码,Spring对此进行了抽象——使用模板来消除样板式代码 ,JdbcTemplate承担了简化数据库访问这块的任务。
@Slf4j @Repository public class FooDao { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private SimpleJdbcInsert simpleJdbcInsert; public void insertData() { Arrays.asList("b", "c").forEach(bar -> { jdbcTemplate.update("INSERT INTO FOO (BAR) VALUES (?)", bar); }); HashMap<String, String> row = new HashMap<>(); row.put("BAR", "d"); Number id = simpleJdbcInsert.executeAndReturnKey(row); log.info("ID of d: {}", id.longValue()); } public void listData() { log.info("Count: {}", jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO", Long.class)); List<String> list = jdbcTemplate.queryForList("SELECT BAR FROM FOO", String.class); list.forEach(s -> log.info("Bar: {}", s)); List<Foo> fooList = jdbcTemplate.query("SELECT * FROM FOO", new RowMapper<Foo>() { @Override public Foo mapRow(ResultSet rs, int rowNum) throws SQLException { return Foo.builder() .id(rs.getLong(1)) .bar(rs.getString(2)) .build(); } }); fooList.forEach(f -> log.info("Foo: {}", f)); } }
JdbcTemplate
NamedParameterJdbcTemplate
public void batchInsert() { jdbcTemplate.batchUpdate("INSERT INTO FOO (BAR) VALUES (?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setString(1, "b-" + i); } @Override public int getBatchSize() { return 2; } }); List<Foo> list = new ArrayList<>(); list.add(Foo.builder().id(100L).bar("b-100").build()); list.add(Foo.builder().id(101L).bar("b-101").build()); namedParameterJdbcTemplate .batchUpdate("INSERT INTO FOO (ID, BAR) VALUES (:id, :bar)", SqlParameterSourceUtils.createBatch(list)); }
原文:https://www.cnblogs.com/zycb/p/10828956.html