一、JDBC问题回顾及问题分析
我们为何使用MyBatis
JDBC问题总结
1、 数据库连接创建、释放频繁造成系统资源浪费,从⽽影响系统性能。
2、 Sql语句在代码中硬编码,造成代码不易维护,实际应⽤中sql变化的可能较⼤,sql变动需要改变java代码。
3、 使⽤preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不⼀定,可能多也可能少,修改sql还要修改代码,系统不易维护。
4、 对结果集解析存在硬编码(查询列名),sql变化导致解析代码变化,系统不易维护,如果能将数据 库记录封装成pojo对象解析⽐较⽅便。
二、设计自定义持久层框架
自定义持久层框架思路
自定义持久层框架使用端
首先完成配置文件编写
UserMapper.xml
<mapper namespace="user">
<!-- 唯一标识 user.selectList 下面同理namespace.id -->
<select id="selectList" resultType="com.lagou.pojo.User">
select * from user
</select>
<select id="selectOne" resultType="com.lagou.pojo.User" paramterType="com.lagou.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
......
</mapper>
sqlMapConfig.xml
<configuration>
<dataSource>
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///zdy_mybatis?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</dataSource>
<!-- 在Config.xml中,将Mapper.xml路径进行配置,这样只需要读取Config.xml就可以间接读取到Mapper.xml内容,省略大量的Mapper.xml文件读取-->
<mapper resource="UserMapper.xml"></mapper>
</configuration>
测试类
public class IPersistenceTest {
@Test
public void test() throws PropertyVetoException, DocumentException, IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("user.selectOne", new User("1", "张三"));
System.out.println(user);
List<User> userList = sqlSession.selectList("user.selectList");
System.out.println(userList);
}
}
自定义持久层框架端
1. 根据配置文件路径,将配置文件加载为字节输入流,存储在内存中
Resource.java
public class Resources {
// 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
public static InputStream getResourceAsStream(String path) {
InputStream inputStream = Resources.class.getClassLoader().getSystemResourceAsStream("");
return inputStream;
}
}
2. 首先定义两个bean,用于存储配置文件内容
MappedStatement.java
public class MappedStatement {
// id标识
private String id;
// 返回值类型
private String resultType;
// 参数类型
private String paramterType;
// sql语句
private String sql;
// 省略getter和setter方法
}
Configuration.java
public class Configuration {
// 数据源信息直接封装到DataSource对象中
private DataSource dataSource;
// Map用于存储多条sql封装信息,key:statementId value:封装好的MappedStatement
private Map<String, MappedStatement> mappedStatementMap = new HashMap<>();
}
3. 创建SqlSessionFactoryBuilder对象,读取配置文件,生产SqlSession
SqlSessionFactoryBuilder.java
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in) throws PropertyVetoException, DocumentException {
// 第一步:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
XmlConfigBuilder xmlConfigBuilder = new XmlConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
// 第二步:创建SqlSessionFactory对象,工厂类:生产SqlSession会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
第一步:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
XmlConfigBuilder.xml:读取Config.xml中的内容,间接读取到Mapper.xml文件
public class XmlConfigBuilder {
// 成员变量生产Configuration,以便其他类使用
private Configuration configuration;
public XmlConfigBuilder() {
this.configuration = new Configuration();
}
// 该方法就是使用dom4j对配置文件进行解析,封装Configuration对象
public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
Document document = new SAXReader().read(in);
// 拿去根标签 <configuration>
Element rootElement = document.getRootElement();
// 用拿到的根标签根据XPath表达式,获取子标签信息
// 1. 首先获取数据源信息
List<Element> list = rootElement.selectNodes("//property");
// 遍历list,拿到每一个name和value,封装进Properties中
Properties properties = new Properties();
for (Element element : list) {
String name = element.attributeValue("name");
String value = element.attributeValue("value");
properties.setProperty(name, value);
}
// 使用数据库连接池
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
comboPooledDataSource.setUser(properties.getProperty("username"));
comboPooledDataSource.setPassword(properties.getProperty("password"));
// 将数据源信息封装进入Configuration对象中
configuration.setDataSource(comboPooledDataSource);
// 2. 获取Mapper.xml信息
// 拿到路径,加载为字节输入流,dom4j再进行解析
List<Element> mapperList = rootElement.selectNodes("//mapper");
// 获取Mapper.xml路径
for (Element element : mapperList) {
String mapperPath = element.attributeValue("resource");
InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
XmlMapperBuider xmlMapperBuider = new XmlMapperBuider(configuration);
xmlMapperBuider.parse(resourceAsStream);
}
return configuration;
}
}
XmlMapperBuider.xml:读取到Mapper.xml文件内容
public class XmlMapperBuider {
private Configuration configuration;
public XmlMapperBuider(Configuration configuration) {
this.configuration = configuration;
}
public void parse(InputStream in) throws DocumentException {
Document document = new SAXReader().read(in);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List<Element> list = rootElement.selectNodes("//select");
for (Element element : list) {
String id = element.attributeValue("id");
String resultType = element.attributeValue("resultType");
String paramterType = element.attributeValue("paramterType");
String sqlText = element.getTextTrim();
// 将解析出来的内容封装到MappedStatement对象中
MappedStatement mappedStatement = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParamterType(paramterType);
mappedStatement.setSql(sqlText);
// 将封装好的MappedStatement放入Configuration对象中
String key = namespace + "." + id;
configuration.getMappedStatementMap().put(key, mappedStatement);
}
}
}
第二步:创建SqlSessionFactory对象,工厂类:生产SqlSession会话对象
SqlSession.java
public interface SqlSessionFactory {
public SqlSession openSession();
}
DefaultSqlSession.java
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
// configuration进行向下传递
return new DefaultSqlSession(configuration);
}
}
4. 创建SqlSession接口及其实现类,定义crud操作
SqlSession.java
public interface SqlSession {
// statementId: namespace.id
public <E> List<E> selectList(String statementId, Object... params);
public <T> T selectOne(String statementId, Object... params);
}
DefaultSqlSession.java
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) {
// 调用Executor中的query()方法,真正执行sql
Executor executor = new SimpleExecutor();
List<Object> list = executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
return (List<E>) list;
}
@Override
public <T> T selectOne(String statementId, Object... params) {
List<Object> objects = selectList(statementId, params);
if (objects.size() == 1) {
return (T) objects.get(0);
} else {
throw new RuntimeException("返回结果为空或返回结果过多");
}
}
}
5. 创建Executor接口及其实现类SimpleExecutor,定义query()方法
query()方法实则就是JDBC代码,真正执行sql
Executor.java
public interface Executor {
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException;
}
SimpleExecutor.java
public class SimpleExecutor implements Executor {
@Override
public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
// JDBC步骤
// 1. 获取连接对象
Connection connection = configuration.getDataSource().getConnection();
// 2. 获取SQL语句:select * from user where id = #{id} and username = #{username}
// 我们需要对sql语句中的#{}进行解析,替换为?,这样才能交给JDBC进行处理,还要存储解#{}中的值,以便后续设置参数
// 创建一个BoundSql来存储已经解析的Sql和#{}中的值
BoundSql boundSql = getBoundSql(mappedStatement.getSql());
// 3. 获取预处理对象:PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParsedSql());
// 4. 设置参数
// 这里我们使用反射技术,因为MappedStatement当中存储了参数的全路径类名,所以可以读取到该类,并进行操作
String paramterType = mappedStatement.getParamterType();
Class<?> paramterTypeClass = getClassType(paramterType);
// 根据#{}中解析出来的字段名,通过反射,获取传入参数中该字段的值
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
String content = parameterMapping.getContent(); // 字段名
Field field = paramterTypeClass.getDeclaredField(content);
// 暴力反射
field.setAccessible(true);
Object o = field.get(params[0]);
// 设置参数
preparedStatement.setObject(i+1, o);
}
// 5. 执行Sql
ResultSet resultSet = preparedStatement.executeQuery();
// 6. 封装返回结果集
String resultType = mappedStatement.getResultType();
Class<?> resultTypeClass = getClassType(resultType);
List<Object> resultList = new ArrayList<>();
while (resultSet.next()) {
// 根据获取到的Class创建实体
Object o = resultTypeClass.newInstance();
// 获取结果集的元数据,包括了列名
ResultSetMetaData metaData = resultSet.getMetaData();
// 对每一个列字段进行值的填充
for (int i = 1; i <= metaData.getColumnCount(); i++) {
// 字段名
String columnName = metaData.getColumnName(i);
// 字段值
Object columnValue = resultSet.getObject(columnName);
// 使用内省(反射),根据数据库表与实体的对应关系,完成封装
// PropertyDescriptor内省库中的类,根据传入的列名和类,获取到该类中该列名的读写方法
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
Method writeMethod = propertyDescriptor.getWriteMethod();
// 通过invoke方法,将列值填充到对象o中
writeMethod.invoke(o, columnValue);
}
resultList.add(o);
}
return (List<E>) resultList;
}
private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
if (paramterType != null) {
Class<?> aClass = Class.forName(paramterType);
return aClass;
}
return null;
}
/**
* 完成对#{}的解析:将#{}替换为?,解析出#{}中的值进行存储
* @param sql
* @return
*/
public BoundSql getBoundSql(String sql) {
// 这里借助Mybatis中的类方法,对Sql语句进行解析
// 标记处理类:使用标记配置解析器来完成占位符的解析工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
// 解析出来的Sql
String parsedSql = genericTokenParser.parse(sql);
// #{}里面解析出来的值的列表
List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
return new BoundSql(parsedSql, parameterMappings);
}
}
扩充:Sql解析时使用到的Mybatis中的类
TokenHandler.java
public interface TokenHandler {
String handleToken(String content);
}
ParameterMappingTokenHandler.java
ublic class ParameterMappingTokenHandler implements TokenHandler {
private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
// context是参数名称 #{id} #{username}
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
private ParameterMapping buildParameterMapping(String content) {
ParameterMapping parameterMapping = new ParameterMapping(content);
return parameterMapping;
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
public void setParameterMappings(List<ParameterMapping> parameterMappings) {
this.parameterMappings = parameterMappings;
}
}
GenericTokenParser.java
public class GenericTokenParser {
private final String openToken; //开始标记
private final String closeToken; //结束标记
private final TokenHandler handler; //标记处理器
public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
this.openToken = openToken;
this.closeToken = closeToken;
this.handler = handler;
}
/**
* 解析${}和#{}
* @param text
* @return
* 该方法主要实现了配置文件、脚本等片段中占位符的解析、处理工作,并返回最终需要的数据。
* 其中,解析工作由该方法完成,处理工作是由处理器handler的handleToken()方法来实现
*/
public String parse(String text) {
// 验证参数问题,如果是null,就返回空字符串。
if (text == null || text.isEmpty()) {
return "";
}
// 下面继续验证是否包含开始标签,如果不包含,默认不是占位符,直接原样返回即可,否则继续执行。
int start = text.indexOf(openToken, 0);
if (start == -1) {
return text;
}
// 把text转成字符数组src,并且定义默认偏移量offset=0、存储最终需要返回字符串的变量builder,
// text变量中占位符对应的变量名expression。判断start是否大于-1(即text中是否存在openToken),如果存在就执行下面代码
char[] src = text.toCharArray();
int offset = 0;
final StringBuilder builder = new StringBuilder();
StringBuilder expression = null;
while (start > -1) {
// 判断如果开始标记前如果有转义字符,就不作为openToken进行处理,否则继续处理
if (start > 0 && src[start - 1] == '\\') {
builder.append(src, offset, start - offset - 1).append(openToken);
offset = start + openToken.length();
} else {
//重置expression变量,避免空指针或者老数据干扰。
if (expression == null) {
expression = new StringBuilder();
} else {
expression.setLength(0);
}
builder.append(src, offset, start - offset);
offset = start + openToken.length();
int end = text.indexOf(closeToken, offset);
while (end > -1) {存在结束标记时
if (end > offset && src[end - 1] == '\\') {//如果结束标记前面有转义字符时
// this close token is escaped. remove the backslash and continue.
expression.append(src, offset, end - offset - 1).append(closeToken);
offset = end + closeToken.length();
end = text.indexOf(closeToken, offset);
} else {//不存在转义字符,即需要作为参数进行处理
expression.append(src, offset, end - offset);
offset = end + closeToken.length();
break;
}
}
if (end == -1) {
// close token was not found.
builder.append(src, start, src.length - start);
offset = src.length;
} else {
//首先根据参数的key(即expression)进行参数处理,返回?作为占位符
builder.append(handler.handleToken(expression.toString()));
offset = end + closeToken.length();
}
}
start = text.indexOf(openToken, offset);
}
if (offset < src.length) {
builder.append(src, offset, src.length - offset);
}
return builder.toString();
}
}
ParameterMapping.java
public class ParameterMapping {
private String content;
public ParameterMapping(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
三、优化自定义持久层框架
问题:
解决:
在使用端创建接口
IUserDao.java
public interface IUserDao {
//查询所有用户
public List<User> findAll() throws Exception;
//根据条件进行用户查询
public User findByCondition(User user) throws Exception;
}
在SqlSession中,增加getMapper()方法
通过getMapper()方法,使用代理模式,用代理对象来对Mapper中的方法进行执行
public interface SqlSession {
//查询所有
public <E> List<E> selectList(String statementid,Object... params) throws Exception;
//根据条件查询单个
public <T> T selectOne(String statementid,Object... params) throws Exception;
//为Dao接口生成代理实现类
public <T> T getMapper(Class<?> mapperClass);
}
DefaultSqlSession.java
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
......
@Override
public <T> T getMapper(Class<?> mapperClass) {
// 使用JDK动态代理来为Dao接口生成代理对象,并返回
Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
@Override
/**
* proxy:当前代理对象的引用;method:当前被调用方法的引用;args:传递的参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 底层都还是去执行JDBC代码 //根据不同情况,来调用selctList或者selectOne
// 准备参数 1:statmentid :sql语句的唯一标识:namespace.id= 接口全限定名.方法名
// 方法名:findAll
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String statementId = className+"."+methodName;
// 准备参数2:params:args
// 获取被调用方法的返回值类型
Type genericReturnType = method.getGenericReturnType();
// 判断是否进行了 泛型类型参数化(泛型化即为集合) -- 简单判断
if(genericReturnType instanceof ParameterizedType){
List<Object> objects = selectList(statementId, args);
return objects;
}
return selectOne(statementId,args);
}
});
return (T) proxyInstance;
}
}
修改使用端代码
首先Mapper.xml中的namespace改为接口全限定类名
<mapper namespace="com.lagou.dao.IUserDao">
<!--sql的唯一标识:namespace.id来组成 : statementId-->
<select id="findAll" resultType="com.lagou.pojo.User" >
select * from user
</select>
<select id="findByCondition" resultType="com.lagou.pojo.User" paramterType="com.lagou.pojo.User">
select * from user where id = #{id} and username = #{username}
</select>
</mapper>
测试类测试:
public class IPersistenceTest {
@Test
public void test() throws Exception {
InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
SqlSession sqlSession = sqlSessionFactory.openSession();
//调用
User user = new User();
user.setId(1);
user.setUsername("张三");
// 直接通过getMapper方法,获取到接口代理对象,然后调用接口中的方法即可
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
List<User> all = userDao.findAll();
for (User user1 : all) {
System.out.println(user1);
}
}
}