🌲 spring - jdbc
🍁 spring - jdbc - 简介
Spring-Jdbc
是对Jdbc的封装
,解决了Jdbc的如下问题
简化了调用流程
(采用模版设计模式封装)异常转换
,使用ErrorCodeSqlExceptionTranslator
把SQLException(检查异常)
转换成RuntimeException(非检查异常)
- 把
Connection绑定到当前线程
(ThreadLoal方式),保证了Connection是线程安全
的
🍂 spring - jdbc - API
在使用时候,大概分为三类使用方法,分别是
模板方式
-JdbcTemplate
和NamedParamterTemplate
Support类方式
-JdbcDaoSupport
简化和复用对象(不用写sql,可以复用)
-SimpleJdbcInsert
、SimpleJdbcCall
、SqlMappingQuery
、SqlUpdate
JdbcTemplate
- 查询
- execute() - 执行DDL或者其他SQL
query()
- 执行DQL。一般用于查询多行并传给BeanPropertyRowMapper
queryForObject
- 查询单行单列或者单行多列。queryForList
- 查询多行,返回的类型是List<Map<k,v>>
。- update() - 执行更新。配合
PreparedStatementCreator
和GeneratedKeyHolder
可以获取自增主键
- batchUpdate - 批量更新。使用List或者
BatchUpdateStatementSetter
传入参数。
NamedParamterTemplate
- 支持命名参数SqlParamter
- query() - 更新。可以传入SqlParamterSource
- batchUpdate() - 批量更新。使用SqlParamterSourceUtils传入参数
MapSqlParamterSource
- 把Map封装成SqlParamterSource
BeanPropertySqlParamterSource
- 把Bean封装成SqlParamterSource
JdbcDaoSupport
- 内部有JdbcTemplate,可以继承它
SimpleJdbcInsert
- 执行插入,可以不用写Sql
- withTableName() - 表名
- usingGeneratedKeyColumns - 自增主键
- execute() - 插入
- executeAndReturnKeyHolder - 插入并返回KeyHolder
SimpleJdbcCall
- 调用存储过程、函数
- withProcedureName() - 指定存储过程
- withFunctionName() - 指定函数
- execute() - 执行
SqlMappingQuery
- 可复用查询(可以直接封装到DAO中)
- setsql() - 指定sql
- setDataSource() - 指定datasource
- comiple() - 编译
SqlUpdate
- 可复用更新
- declareParamter() - 声明参数
🌳 Spring -jdbc - datasource
Spring提供了datasource的实现,测试时候使用很方便
。
DriverManagerDatasource
- 每次获取新的连接SingleConnectionDatasource
- 只有一个连接(线程安全问题,只能做测试)DataSourceUtils
- 获取连接,然后把连接绑定到线程(TransiactionManager和JdbcTemplate使用它)
🍀 Spring - jdbc - template
🌱 JdbcTempalte使用
@Service
public class AreaService {
// 注入jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* queryForObject - 查询单行
*/
public int count() {
// 1. 查询
Integer integer = jdbcTemplate.queryForObject("select count(*) from tb_area where id > ?", Integer.class, 1);
// 2. 返回
return integer;
}
/*
* query - 查询多行,配合BeanPropertyRowMapper完成结果集映射
* */
public List<Area> queryAreaById() {
// 1. 查询
List<Area> area = jdbcTemplate.query("select * from tb_area where id > 1", BeanPropertyRowMapper.newInstance(Area.class));
// 2. 返回
return area;
}
/*
* queryForList - 查询多行,返回List<Map<String,Object>>
* */
public List<Map<String,Object>> queryAreaList() {
// 1. 查询
final List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from tb_area where id= 1");
// 2. 返回
return list;
}
/*
* update - 插入,配合PreparedStatementCreator和GenderatedKeyHolder - 获取自增主键
* */
public int insert() {
// 1. 创建KeyHolder
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
// 2. 执行查询
int update = jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
// 这里设置了获取哪个column作为primarykey
PreparedStatement ps = con.prepareStatement("insert into tb_area values(null,'南aa校区',0,?,?)",