11. Spring JdbcTemplate基本使用
11.1 JdbcTemplate概述
这是Spring框架中提供的一个对象,是对元素繁琐的Jdbc API对象的简单封装。
11.2 JdbcTemplate开发步骤
1)导入spring-jdbc和spring-tx坐标
2)创建数据库表和实体
3)创建JdbcTemplate对象
4)执行数据库操作
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT%2B8");
dataSource.setUsername("root");
dataSource.setPassword("664223");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
applicationContext.xml配置跟前面的数据库配置相同
11.3 常用方法
- query(sql, new BeanPropertyRowMapper<查询表对应的类>(.class))
- query(sql, new BeanPropertyRowMapper<查询表对应的类>(.class), …)
- update(sql, …) (…代表sql中 **?**对应的值)
- delete(sql, …)
11.4 知识要点
1)导入spring-jdbc和spring-tx坐标
2)创建数据库和实体
3)创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = new JdbcTemplate();
JdbcTemplate.setDataSource(dataSource);
4)执行数据库操作
- 更新操作(添加和删除):
jdbc.Template.update(sql, params);
- 查询操作:
jdbcTemplate.query(sql, Mapper, Params);
jdbcTemplate.queryForObject(sql, Mapper, params);