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();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
如上一个jdbc的写法,存在两个缺点:
硬编码:不管是sql语句,还是参数,还是取值,都是硬编码,不好维护。
链接频繁创建和释放:每次访问都会创建新的链接,用完后释放,造成系统资源浪费。
解决办法:
二、自定义mybatis框架 业务项目A可以通过连接池管理链接。
可以用xml文件,将sql等信息配置,通过反射等技术实现动态映射。
1、定义全局配置文件sqlMapConfig.xml来存放数据源信息; 定义Mapper.xml来动态配置sql语句,比如,定义UserMapper.xml操作User。
sqlMapConfig.xml:
UserMapper.xml:
select * from user where id = #{id} and username =#{username}
User实体:
public class User {
private Integer id;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + ''' +
'}';
}
}
持久层框架项目B
在业务项目A中配置了xml文件,持久层框架要做的事,就是将配置文件通过流的方式读取, 并创建javaBean,才能传递使用。具体流程:
导入相关依赖:
UTF-8 UTF-8 1.8 1.8 1.8 mysql mysql-connector-java5.1.17 c3p0 c3p00.9.1.2 log4j log4j1.2.12 junit junit4.10 dom4j dom4j1.6.1 jaxen jaxen1.1.6
创建MappedStatement类对应mapper.xml中的每个sql标签:
public class MappedStatement {
//id标识
private String id;
//返回值类型
private String resultType;
//参数值类型
private String paramterType;
//sql语句
private String sql;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
public String getParamterType() {
return paramterType;
}
public void setParamterType(String paramterType) {
this.paramterType = paramterType;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
创建Configuration类对应sqlMapConfig.xml,封装数据源信息
public class Configuration {
private DataSource dataSource;
Map mappedStatementMap = new HashMap<>();
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map getMappedStatementMap() {
return mappedStatementMap;
}
public void setMappedStatementMap(Map mappedStatementMap) {
this.mappedStatementMap = mappedStatementMap;
}
}
如上,使用DataSource封装xml中的数据库信息,另外,在mapper.xml中有多个select标签,所以这里用map封装到一起传递,后续可以选择具体的某一个来填充业务参数。
有了承载xml的java类后,就需要通过流,读取到对应的javaBean中。
定义Resource类,读取配置文件为流:
import java.io.InputStream;
public class Resources {
// 根据配置文件的路径,将配置文件加载成字节输入流,存储在内存中
public static InputStream getResourceAsSteam(String path){
InputStream resourceAsStream = Resources.class.getClassLoader().getResourceAsStream(path);
return resourceAsStream;
}
}
定义XMLConfigBuilder类,将流中的信息读取到Configuration中
public class XMLConfigBuilder {
private Configuration configuration;
public XMLConfigBuilder() {
this.configuration = new Configuration();
}
public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
Document document = new SAXReader().read(inputStream);
//
Element rootElement = document.getRootElement();
List list = rootElement.selectNodes("//property");
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.setDataSource(comboPooledDataSource);
//mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
List mapperList = rootElement.selectNodes("//mapper");
for (Element element : mapperList) {
String mapperPath = element.attributeValue("resource");
InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperPath);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
xmlMapperBuilder.parse(resourceAsSteam);
}
return configuration;
}
}
定义XMLMapperBuilder,将mapper.xml的流信息读取到MappedStatement,并设置到Configuration的map属性中
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class XMLMapperBuilder {
private Configuration configuration;
public XMLMapperBuilder(Configuration configuration) {
this.configuration =configuration;
}
public void parse(InputStream inputStream) throws DocumentException {
Document document = new SAXReader().read(inputStream);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributeValue("namespace");
List 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 = new MappedStatement();
mappedStatement.setId(id);
mappedStatement.setResultType(resultType);
mappedStatement.setParamterType(paramterType);
mappedStatement.setSql(sqlText);
String key = namespace+"."+id;
configuration.getMappedStatementMap().put(key,mappedStatement);
}
}
}
上面的两个类,可以把xml中的配置读取到Configuration中,在哪里调用的呢?
首先创建一个SqlSessionFactoryBuilder,该类的作用是一个建造者,通过它调用读取配置,得到Configuration后,再创建出一个SqlSessionFactory工厂类,使用该工厂去创建SqlSession,在此过程中依次传递Configuration。
最终在SqlSession中,执行查询。
SqlSessionFactoryBuilder:
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in) throws DocumentException, PropertyVetoException {
// 第一:使用dom4j解析配置文件,将解析出来的内容封装到Configuration中
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder();
Configuration configuration = xmlConfigBuilder.parseConfig(in);
// 第二:创建sqlSessionFactory对象:工厂类:生产sqlSession:会话对象
DefaultSqlSessionFactory defaultSqlSessionFactory = new DefaultSqlSessionFactory(configuration);
return defaultSqlSessionFactory;
}
}
SqlSessionFactory及实现类:
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及实现类:
public interface SqlSession {
//查询所有
public List selectList(String statementid,Object... params) throws Exception;
//根据条件查询单个
public T selectOne(String statementid,Object... params) throws Exception;
}
import java.lang.reflect.*;
import java.util.List;
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration) {
this.configuration = configuration;
}
@Override
public List selectList(String statementid, Object... params) throws Exception {
//将要去完成对simpleExecutor里的query方法的调用
SimpleExecutor simpleExecutor = new SimpleExecutor();
MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
List
如上在sqlSessiion中,通过传入的statementid,可以获取到Configuration中具体的mappedStatement,也就是拿到了具体的sql语句,通过参数等可以开始查询了。 在这里,再把查询的过程抽取到一个执行器SimpleExecutor中去具体执行:
Executor及实现类:
public interface Executor {
public List query(Configuration configuration,MappedStatement mappedStatement,Object... params) throws Exception;
}
public class simpleExecutor implements Executor {
@Override //user
public List query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
// 1. 注册驱动,获取连接
Connection connection = configuration.getDataSource().getConnection();
// 2. 获取sql语句 : select * from user 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 paramterType = mappedStatement.getParamterType();
Class> paramtertypeClass = getClassType(paramterType);
List parameterMappingList = boundSql.getParameterMappingList();
for (int i = 0; i < parameterMappingList.size(); i++) {
ParameterMapping parameterMapping = parameterMappingList.get(i);
String content = parameterMapping.getContent();
//反射
Field declaredField = paramtertypeClass.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);
ArrayList objects = new ArrayList<>();
// 6. 封装返回结果集
while (resultSet.next()){
Object o =resultTypeClass.newInstance();
//元数据
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);
}
return (List) objects;
}
private Class> getClassType(String paramterType) throws ClassNotFoundException {
if(paramterType!=null){
Class> aClass = Class.forName(paramterType);
return aClass;
}
return null;
}
private BoundSql getBoundSql(String sql) {
//标记处理类:配置标记解析器来完成对占位符的解析处理工作
ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
//解析出来的sql
String parseSql = genericTokenParser.parse(sql);
//#{}里面解析出来的参数名称
List parameterMappings = parameterMappingTokenHandler.getParameterMappings();
BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
return boundSql;
}
}
如上,在执行器中,通过configuration得到数据库链接信息和mappedStatement中的sql,就可以通过jdbc执行了。
要注意的是,mappedStatement取出的sql的参数,是#{}这种样式:
select * from user where id = #{id} and username = #{username}
jdbc需要的是?的样式:
select * from user where id = ? and username = ?
这里就是通过getBoundSql这个方法,把sql每个 #{} 替换成 ? ,并把#中的参数名称 按顺序存放在一个list中。 并把解析后结果存放到BoundSql中保存返回,然后在executor中,遍历list中每个参数名,通过反射技术,在传递的参数类型(User对象)中获取到具体的值,给preparedStatement中每个?赋值。
BoundSql:存放解析后的sql和参数名列表
public class BoundSql {
//解析过后的sql
private String sqlText;
//解析sql后,将每个#中的参数名存放下来
private List parameterMappingList = new ArrayList<>();
public BoundSql(String sqlText, List parameterMappingList) {
this.sqlText = sqlText;
this.parameterMappingList = parameterMappingList;
}
public String getSqlText() {
return sqlText;
}
public void setSqlText(String sqlText) {
this.sqlText = sqlText;
}
public List getParameterMappingList() {
return parameterMappingList;
}
public void setParameterMappingList(List parameterMappingList) {
this.parameterMappingList = parameterMappingList;
}
}
对于查询后的结果ResultSet,也是根据mappedStatement中配置的返回类型创建返回对象,通过反射、内省技术,动态将值设置到返回对象中。
有了上面的流程后,在业务项目A中,引入持久层框架B的依赖,便可以实现调用了
@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("张三");
User user2 = sqlSession.selectOne("user.selectOne", user);
System.out.println(user2);
List users = sqlSession.selectList("user.selectList");
for (User user1 : users) {
System.out.println(user1);
}
}



