一、jdbc回顾
- 首先来回顾一下使用jdbc操作数据库的过程
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动类获取数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis? characterEncoding=utf-8", "root", "root");
// 定义sql语句,?表示占位符
String sql = "select * from user where username = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第一个参数为sql语句中占位符的序号,第二个参数为相应占位符的值
preparedStatement.setString(1, "tom");
// 向sql发出sql查询,获得查询结果集
resultSet = preparedStatement.executeQuery();
// 遍历结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装user对象
user.setId(id);
user.setUsername(username);
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- jdbc问题总结
- 数据库连接创建、释放频繁,造成系统资源浪费,影响性能
- sql语句在代码中硬编码,造成代码不易维护,实际sql变动较多,需要经常改java代码
- 使用preparedStatement向占位符传参存在硬编码,系统不易维护
- 对结果集解析存在硬编码,系统不易维护,如果能将数据库记录封装成pojo对象解析比较方便
- 问题解决思路
- 数据库创捷、释放频繁:使用连接池
- sql语句及数据库连接信息硬编码问题:使用配置文件
- 手动解析封装返回结果集问题:利用反射、内省等
二、自定义框架设计
使用端:
- 提供核心配置文件
- sqlMapConfig.xml:存放数据源信息,引入mapper.xml
- mapper.xml:sql语句
框架端:
- 读取配置文件
读取文件,获得文件流在,将信息封装为JavaBean对象。
- Configuration:存放数据库连接信息,以及所有的MappedStatement对象,使用map结构来保存Map<唯一标识,MappedStatement>,语句唯一标识:namespace+id
- MappedStatement:存放sql语句,以及参数类型,返回值类型,statement类型,sql语句唯一标识(namespace+id)
- 解析配置文件
新建sqlSessionFactoryBuild类,编写biuld方法 sqlSessionFactory build(),build方法做两件事:
- 使用dom4j解析配置文件sqlMapperConfig.xml和Mapper.xml,将解析内容封装到Configuration和MappedStatement对象
- 创建SqlsessionFactory的实现类DefaultSqlsessionFactory
- 新建sqlSessionFactory
新建sqlSessionFactory接口及其实现类DefaultSqlsessionFactory,类中包含方法:
SqlSession openSession(),该方法创建SqlSession的实现类
- 新建sqlSession接口及其实现类:主要封装CRUD方法
- selectList(String statementId, Object param);查询所有
- selectOne(String statementId, Object param);查询单个
- close();释放资源
通过SqlsessionFactory创建SqlSession的实现类
涉及到的设计模式:
- 构建者模式
- 工厂模式
- 代理模式