1.1 分析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语句中参数的序号(从 1 开始),第二个参数为设置的参数值
preparedStatement.setString(1, "tom");
// 向数据库发出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();
原始jdbc开发存在的问题如下:
1 、
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动管理类获取数据库链接
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?
characterEncoding = utf - 8", " root", " root");
数据库连接创建、释放频繁造成系统资源浪费,从而影响系统性能。
2 、
String sql = "select * from user where username = ?";
Sql语句在代码中硬编码,造成代码不易维护,实际应用中sql变化的可能较大,sql变动需要改变 java代码。
3 、
String sql = "select * from user where username = ?";
使用preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不一定,可能 多也可能少,修改sql还要修改代码,系统不易维护。
4 、
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装User
user.setId(id);
user.setUsername(username);
}
对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据 库记录封装成pojo对象解析比较方便。
1.2 问题解决思路
①使用数据库连接池初始化连接资源
②将sql语句抽取到xml配置文件中
③使用反射、内省等底层技术,自动将实体与表进行属性与字段的自动映射
1.3 自定义框架设计
使用端:
提供核心配置文件:
sqlMapConfig.xml : 存放数据源信息,引入mapper.xml
Mapper.xml : sql语句的配置文件信息
框架端:本质是对JDBC代码进行了封装
1.**加载配置文件:**根据配置文件的路径,加载配置文件成字节输入流,存储在内存中,创建Resources类 。
2.读取配置文件:
读取完成以后以流的形式存在,我们不能将读取到的配置信息以流的形式存放在内存中,不好操作,可以创建两个javaBean
来存储:
第一:Configuration : 存放数据库基本信息、Map<唯一标识,Mapper> 唯一标识:namespace + "."
+id
第二:MappedStatement:映射配置类,存放mapper.xml解析出来的内容sql语句、statement类型、输入参数java类型、输出参数java类型
3.解析配置文件:
创建sqlSessionFactoryBuilder类:
方法:build():
第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration和MappedStatement中
第二:创建SqlSessionFactory对象;生产sqlSession:会话对象(工厂模式)
4.创建SqlSessionFactory:
方法:openSession() : 获取sqlSession接口的实现类实例对象
5.创建sqlSession接口及实现类:主要封装crud方法
方法:selectList():查询所有
6.创建Executor接口及实现类SimpleExecutor实现类
方法:query():执行的就是JDBC代码
涉及到的设计模式:
Builder构建者设计模式、工厂模式、代理模式
1.4 自定义框架实现
使用端项目
创建 sqlMapConfig.xml
<configuration>
<!--数据库配置信息-->
<datasource>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///fxf_mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</datasource>
<!--存放mapper.xml的全路径-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
解释如下:
<configuration>
: 这是配置文件的根标签,用于包含所有的配置信息。<datasource>
: 这是数据源配置标签,用于指定数据库连接的相关信息。<property>
: 这是属性标签,用于设置具体的属性值。
创建Usermapper.xml
<mapper namespace="User">
<select id="selectOne" paramterType="com.lagou.pojo.User"
resultType="com.amber.pojo.User">
select * from user where id = #{id} and username =#{username}
</select>
<select id="selectList" resultType="com.amber.pojo.User">
select * from user
</select>
</mapper>
- 在这个例子中,
selectOne
、sel 是查询语句的唯一标识符。 parameterType="com.lagou.pojo.User"
指定了输入参数的类型为com.lagou.pojo.User
。resultType="com.lagou.pojo.User"
指定了查询结果的类型为com.lagou.pojo.User
。select * from user where id = #{id} and username = #{username}
: 这是实际的 SQL 查询语句,用于从user
表中查询满足指定条件的记录。#{id}
和#{username}
是占位符,用于表示输入参数的值。
测试方法:
public class IPersistenceTest {
@Test
public void test() throws PropertyVetoException, DocumentException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//调用
User user = new User();
user.setId(1);
user.setName("张三");
User user2 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user2);
}
}
底层原理:反射
- 输入参数映射:MyBatis 使用了 Java 的
反射机制
,通过解析parameterType
指定的类型信息,将传入的参数对象与 SQL 语句中的占位符进行匹配。在查询执行时,会根据参数对象的属性名和占位符的名称进行映射,将参数值设置到对应的占位符上。 - 结果集映射:MyBatis 通过查询结果集的元数据,结合
resultType
指定的类型信息,创建一个对应的结果对象。然后,根据结果集的列名或者列索引,使用反射机制
将查询结果中的数据映射到结果对象的属性上。
通过这种映射机制,MyBatis 实现了输入参数和查询结果的自动映射,简化了开发过程,并提供了灵活性和可维护性。同时,可以根据业务需求和数据库结构的变化,灵活调整参数类型和结果类型的映射关系,以适应不同的场景。
User实体
@data
public class User {
//主键标识
private Integer id;
//用户名
private String username;
}
框架端项目
Resources
public class Resources {
//根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
public static InputStream getResourceAsStream(String path) {
//Resources.class.getClassLoader()获取类加载器,将path转成流返回
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
Configuration
@Getter
@Setter
public class Configuration {
private DataSource dataSource;
Map<String,MappedStatement> mappedStatementMap = new HashMap<>();
}
MappedStatement
@Data
public class MappedStatement {
//id标识
private String id;
//返回值类型
private String resultType;
//参数值类型
private String parameterType;
//sql语句
private String sql;
}
Resources
public class Resources {
//根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
public static InputStream getResourceAsStream(String path) {
//Resources.class.getClassLoader()获取类加载器,将path转成流返回
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
SqlSessionFactoryBuilder
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in) throws PropertyVetoException, DocumentException {
//第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
//第二:创建sqlSessionFactory对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
XMLConfigBuilder
public class XMLConfigBuilder {
private Configuration configuration;
public XMLConfigBuilder() {
this.configuration = new Configuration();
}
/**
* 使用dom4j解析配置文件,并将解析结果封装到Configuration对象中。
*
* @param inputStream 配置文件的输入流。
* @return 解析后的Configuration对象。
* @throws DocumentException 如果解析XML文档时发生错误。
* @throws PropertyVetoException 如果设置驱动类时发生错误。
*/
public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
// 创建一个SAXReader对象,用于读取XML文件
SAXReader saxReader = new SAXReader();
// 使用SAXReader对象读取XML文档,返回一个Document对象
Document document = saxReader.read(inputStream);
// 获取XML文档的根元素
Element rootElement = document.getRootElement();
// 获取所有名为"property"的子元素
List<Element> propertyElements = rootElement.selectNodes("//property");
// 创建一个Properties对象,用于存储属性名和属性值
Properties properties = new Properties();
// 遍历propertyElements列表,解析属性名和属性值,并存储到properties对象中
for (Element element : propertyElements) {
// 获取属性名和属性值
String name = element.attributeValue("name");
String value = element.attributeValue("value");
// 将属性名和属性值存储到properties对象中
properties.setProperty(name, value);
}
// 创建ComboPooledDataSource对象,用于管理数据库连接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
// 设置数据库驱动类
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
// 设置JDBC连接URL
comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
// 设置数据库用户名
comboPooledDataSource.setUser(properties.getProperty("username"));
// 设置数据库密码
comboPooledDataSource.setPassword(properties.getProperty("password"));
// 将ComboPooledDataSource对象设置到Configuration对象中
configuration.setDataSource(comboPooledDataSource);
// 返回解析后的Configuration对象
return configuration;
}
}
XMLMapperBuilder
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
this.configuration = configuration;
}
/**
* 解析Mapper配置文件,并将解析结果添加到Configuration对象中。
*
* @param in Mapper配置文件的输入流。
* @return 解析后的Configuration对象。
* @throws DocumentException 如果解析XML文档时发生错误。
*/
public Configuration parse(InputStream in) throws DocumentException {
// 创建一个SAXReader对象,用于读取XML文件
SAXReader saxReader = new SAXReader();
// 使用SAXReader对象读取XML文档,返回一个Document对象
Document document = saxReader.read(in);
// 获取XML文档的根元素
Element rootElement = document.getRootElement();
// 获取Mapper的命名空间
String namespace = rootElement.attributeValue("namespace");
// 获取所有名为"select"的子元素
List<Element> selectElements = rootElement.selectNodes("//select");
// 遍历selectElements列表,解析每个<select>元素
for (Element element : selectElements) {
// 获取<select>元素的id、resultType、parameterType属性值以及SQL语句内容
String id = element.attributeValue("id");
String resultType = element.attributeValue("resultType");
String parameterType = element.attributeValue("parameterType");
//获取元素的文本内容
String sqlText = element.getTextTrim();
// 创建MappedStatement对象,用于存储解析结果
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParameterType(parameterType);
mappedStatement.setSql(sqlText);
// 构造 MappedStatement 在 Configuration 中的唯一标识
String key = namespace + "." + id;
// 将MappedStatement 对象添加到 Configuration 的 MappedStatementMap 中
configuration.getMappedStatementMap().put(key, mappedStatement);
}
// 返回解析后的 Configuration 对象
return configuration;
}
}
sqlSessionFactory 接口及DefaultSqlSessionFactory 实现类
public interface SqlSessionFactory {
public SqlSession openSession();
}
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
sqlSession 接口及 DefaultSqlSession 实现类
public interface SqlSession {
//查询所有
<E> List<E> selectList(String statementId, Object... params) throws Exception;
//根据条件查询单个
<E> E selectOne(String statementId, Object... params) throws Exception;
}
public class DefaultSqlSession implements SqlSession{
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public <E> List<E> selectList(String statementId, Object... params) throws Exception {
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
return (List<E>) list;
}
@Override
public <E> E selectOne(String statementId, Object... params) throws Exception {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (E) objects.get(0);
}else {throw new RuntimeException("查询结果为空或者返回结果不止一条");}
}
}
Executor
public interface Executor {
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params);
}
SimpleExecutor
public class SimpleExecutor implements Executor {
@Override
public void execute(Runnable command) {
}
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
//1.注册驱动,获取连接
Connection connection = configuration.getDataSource().getConnection();
//2.获取 sql 语句 :select * from suer where id = #{id} and username = #{username}
//转换sql: select * from user where id = ? and username = ? ,转换的过程中,还需要对#{}里面的值进行解析存储
String sql = mappedStatement.getSql();
BoundSql boundSql = getBoundSql(sql);
//3.获取预处理对象:preparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
//4.设置参数
//获取到了参数的全路径
String parameterType = mappedStatement.getParameterType();
Class<?> parameterTypeClass = getClassType(parameterType);
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();
//反射
Field declaredField = parameterTypeClass.getDeclaredField(content);
//暴力访问
declaredField.setAccessible(true);
//获取参数
Object o = declaredField.get(params[0]);
preparedStatement.setObject(i + 1, o);
}
//5.执行sql
ResultSet resultSet = preparedStatement.executeQuery();
String resultType = mappedStatement.getResultType();
Class<?> resultTypeClass = getClassType(resultType);
Object o = resultTypeClass.newInstance();
ArrayList<Object> objects = new ArrayList<>();
while (resultSet.next()) {
//元数据
ResultSetMetaData metaData = resultSet.getMetaData();
for (int i = 1; i <= metaData.getColumnCount() ; i++) {
//字段名
String columnName = metaData.getColumnName(i);
//字段值
Object value = resultSet.getObject(columnName);
//使用反射或者内省,根据数据库表和实体的对应关系,完成封装
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(o, value);
}
objects.add(o);
}
//5. 封装返回结果集
return (List<E>) objects;
}
private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
if (parameterType != null) {
Class<?> aClass = Class.forName(parameterType);
return aClass;
}
return null;
}
/**
* 完成对#{}的解析工作:1.将#{}使用?进行代替,2.解析出#{}里面的值进行存储
*/
private BoundSql getBoundSql(String sql) {
//标记处理类:配置标记解析器来完成对占位符解析处理工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
//解析出来的sql
String parseSql = genericTokenParser.parse(sql);
//#{}里面解析出来的参数名称
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
return boundSql;
}
}
BoundSql
public class BoundSql {
private String sqlText;
private List<ParameterMapping> parameterMappingList = new ArrayList<>();
public BoundSql(String sqlText, List<ParameterMapping> parameterMappingList) {
this.sqlText = sqlText;
this.parameterMappingList = parameterMappingList;
}
public String getSqlText() {
return sqlText;
}
public void setSqlText(String sqlText) {
this.sqlText = sqlText;
}
public List<ParameterMapping> getParameterMappingList() {
return parameterMappingList;
}
public void setParameterMappingList(List<ParameterMapping> parameterMappingList) {
this.parameterMappingList = parameterMappingList;
}
}