WHUT软工实践(一)
最近学院搞软件实践课程,选的是java后端,要求用ssm。所以简单回顾一下ssm相关内容。
这次手动简单实现一下mybatis。
这次实现以select * from user为例。其他语句的实现方式都是一样的。
mybatis也是在此基础上对所有的sql语句进行了处理。
首先回顾一下基本的mybatis初始化配置
pom文件导包
mybatis配置文件x1
Mapper文件x1
dao层的接口
entity层的实体类
数据库相关
然后:
public class mybatisTest {
public static void main(String[] args) throws IOException {
//读取配置文件信息
InputStream in = Resource.getResourceAsStream("SqlMapConfig.xml");
//建造者
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//建造SqlSession工厂(顺便提一下,这里用的是工程模式)
SqlSessionFactory factory = builder.build(in);
//创建一个新的SqlSession对象
SqlSession session = factory.openSession();
//动态代理UserDao,实现其中方法
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.findAll();
for (User user:users
) {
System.out.println(user.toString());
}
//关闭释放资源
session.close();
in.close();
}
}
试一下结果:啪的一下就搜出来了,很快啊。没什么问题
简单看一下用到的几个工具类:
Resources是class
SqlSessionFactoryBuilder是class
SqlSessionFactory是interface
SqlSession是interface
手动实现mybatis
分别创建相对应上面的class和接口
import java.io.InputStream;
/**
* 使用类加载器读取配置文件的类
*/
public class Resource {
/**
* 根据传入的参数,获取一个节点的输入流
* @param filePath
* @return
*/
public static InputStream getResourceAsStream(String filePath){
return null;
}
}
关于getResourceAsStream()的问题,有一篇写的不错的博客
getResourceAsStream博客地址
import java.io.InputStream;
/**
* 用于创建一个SqlSessionFactory对象
*/
public class SqlSessionFactoryBuilder {
/**
* 根据参数的字节流来构建一个SqlSessionFactory
* @param inputStream
* @return
*/
public SqlSessionFactory build(InputStream inputStream){
//这里报错先不管,反正就是返回一个SqlSessionFactory对象
return new SqlSessionFactory();
}
}
/**
* 创建sqlsession对象的工厂
*/
public interface SqlSessionFactory {
SqlSession openSession();
}
public interface SqlSession {
<T> T getMapper(Class<T> daoInterfaceClass);
void close();
}
至此,基本的模块就创建完成了,接下来进行代码填充。
代码填充
1.Resource:Resource是用来读取mybatis的配置文件的,所以我们利用Resource的类加载器来获取配置文件的输入流
public class Resource {
/**
* 根据传入的参数,获取一个节点的输入流
* @param filePath
* @return
*/
public static InputStream getResourceAsStream(String filePath){
return Resource.class.getClassLoader().getResourceAsStream(filePath);
}
}
2.SqlSession创建过程中:
先解析我们获得的输入流,获得相关配置信息
/**
* 用于解析配置文件
*/
public class XMLConfigBuilder {
/**
* 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
* 使用的技术:
* dom4j+xpath
*/
public static Configuration loadConfiguration(InputStream config){
try{
//定义封装连接信息的配置对象(mybatis的配置对象)
Configuration cfg = new Configuration();
//1.获取SAXReader对象
SAXReader reader = new SAXReader();
//2.根据字节输入流获取Document对象
Document document = reader.read(config);
//3.获取根节点
Element root = document.getRootElement();
//4.使用xpath中选择指定节点的方式,获取所有property节点
List<Element> propertyElements = root.selectNodes("//property");
//5.遍历节点
for(Element propertyElement : propertyElements){
//判断节点是连接数据库的哪部分信息
//取出name属性的值
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
//表示驱动
//获取property标签value属性的值
String driver = propertyElement.attributeValue("value");
cfg.setDriver(driver);
}
if("url".equals(name)){
//表示连接字符串
//获取property标签value属性的值
String url = propertyElement.attributeValue("value");
cfg.setUrl(url);
}
if("username".equals(name)){
//表示用户名
//获取property标签value属性的值
String username = propertyElement.attributeValue("value");
cfg.setUsername(username);
}
if("password".equals(name)){
//表示密码
//获取property标签value属性的值
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
//取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
//遍历集合
for(Element mapperElement : mapperElements){
//判断mapperElement使用的是哪个属性
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){
// System.out.println("使用的是XML");
//表示有resource属性,用的是XML
//取出属性的值
String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/UserDao.xml"
//把映射配置文件的内容获取出来,封装成一个map
Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
//给configuration中的mappers赋值
cfg.setMappers(mappers);
}else{
// System.out.println("使用的是注解");
// //表示没有resource属性,用的是注解
// //获取class属性的值
// String daoClassPath = mapperElement.attributeValue("class");
// //根据daoClassPath获取封装的必要信息
// Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
// //给configuration中的mappers赋值
// cfg.setMappers(mappers);
}
}
//返回Configuration
return cfg;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
config.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 根据传入的参数,解析XML,并且封装到Map中
* @param mapperPath 映射配置文件的位置
* @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
* 以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
*/
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
//1.根据路径获取字节输入流
in = Resource.getResourceAsStream(mapperPath);
//2.根据字节输入流获取Document对象
SAXReader reader = new SAXReader();
Document document = reader.read(in);
//3.获取根节点
Element root = document.getRootElement();
//4.获取根节点的namespace属性取值
String namespace = root.attributeValue("namespace");//是组成map中key的部分
//5.获取所有的select节点
List<Element> selectElements = root.selectNodes("//select");
//6.遍历select节点集合
for(Element selectElement : selectElements){
//取出id属性的值 组成map中key的部分
String id = selectElement.attributeValue("id");
//取出resultType属性的值 组成map中value的部分
String resultType = selectElement.attributeValue("resultType");
//取出文本内容 组成map中value的部分
String queryString = selectElement.getText();
//创建Key
String key = namespace+"."+id;
//创建Value
Mapper mapper = new Mapper();
mapper.setQuerySql(queryString);
mapper.setResultType(resultType);
//把key和value存入mappers中
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
/**
* 根据传入的参数,得到dao中所有被select注解标注的方法。
* 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息
* @param daoClassPath
* @return
*/
/*private static Map<String,Mapper> loadMapperAnnotation(String daoClassPath)throws Exception{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<String, Mapper>();
//1.得到dao接口的字节码对象
Class daoClass = Class.forName(daoClassPath);
//2.得到dao接口中的方法数组
Method[] methods = daoClass.getMethods();
//3.遍历Method数组
for(Method method : methods){
//取出每一个方法,判断是否有select注解
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if(isAnnotated){
//创建Mapper对象
Mapper mapper = new Mapper();
//取出注解的value属性值
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
//获取当前方法的返回值,还要求必须带有泛型信息
Type type = method.getGenericReturnType();//List<User>
//判断type是不是参数化的类型
if(type instanceof ParameterizedType){
//强转
ParameterizedType ptype = (ParameterizedType)type;
//得到参数化类型中的实际类型参数
Type[] types = ptype.getActualTypeArguments();
//取出第一个
Class domainClass = (Class)types[0];
//获取domainClass的类名
String resultType = domainClass.getName();
//给Mapper赋值
mapper.setResultType(resultType);
}
//组装key的信息
//获取方法的名称
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
//给map赋值
mappers.put(key,mapper);
}
}
return mappers;
}*/
}
工具类XMLConfigBuilder可以读取在Resource中获取到的mybatis配置文件的输入流,解析出各个节点的信息,从而拿到配置文件中的数据源信息,Mapper映射文件的位置以及Mapper文件中的sql语句和返回类型等信息。
然后创建一个Configuration类,来封装存储这些拿到解析出的mybatis配置文件的信息。
同时将数据源信息和与sql有关的信息(就是包括Sql语句,与之对应的返回值类型,即把实体类与Sql语句等信息存储到一个map中,因为在真正mybatis执行的时候,存在大量sql数据和大量实体类,map的查找速度要比List快的多)存在Map<String, Mapper>中。
因此,Mapper中就存储Sql语句和返回值类型的全限定类名。
那么String呢?结合Mapper文件可以知道,应该是namesapce+id(即在Dao层中与某实体类所对应的那个实体类Dao的包的位置+那个Dao中方法,这样就可以唯一确定是哪个Dao中的哪个方法,且具有全局唯一性)
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String, Mapper> mappers = new HashMap<String, Mapper>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map mappers){
this.mappers.putAll(mappers);
}
public String getDriver() {
return driver;
}
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Configuration{" +
"driver='" + driver + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
/**
* 用于封装执行的sql语句和结果类型的全限定类名
*/
public class Mapper {
private String querySql;
private String resultType;
public String getQuerySql() {
return querySql;
}
public void setQuerySql(String querySql) {
this.querySql = querySql;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
}
至此,我们已经能够解析读取到mybatis配置文件和Mapper中的信息,并且组装封装到Configuration中,而Configuration中还包含了一个Mapper实体类,用于封装存储sql语句和返回值类型的全限定类名等信息。
现在回到之前的SqlSessionFactoryBuilder中,我们将利用XMLConfigBuilder获得的Configuration当作参数传入给SqlSessionFactory中,但是由于SqlSessionFactory是interface,所以我们创建一个实现类DefaultSqlSessionFactory(名字可以随便起,只要实现SqlSessionFactory接口就可以了)
/**
* 用于创建一个SqlSessionFactory对象
*/
public class SqlSessionFactoryBuilder {
/**
* 根据参数的字节流来构建一个SqlSessionFactory
* @param inputStream
* @return
*/
public SqlSessionFactory build(InputStream inputStream){
Configuration configuration = XMLConfigBuilder.loadConfiguration(inputStream);
return new DefaultSqlSessionFactory(configuration);
}
}
在DefaultSqlSessionFactory中,接收到传过来的Configuration对象,并且在实现的openSession方法中,再将Configuration对象继续传到SqlSession中(注意openSession方法就是用来创建SqlSession对象的)
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration){
this.configuration = configuration;
}
/**
* 用于创建一个新的操作数据库对象
* @return
*/
@Override
public SqlSession openSession() {
return new DefaultSqlSession(configuration);
}
}
因为SqlSession也是接口类型,所以我们继续创建它的实现类DefaultSqlSession
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
public DefaultSqlSession(Configuration configuration){
this.configuration = configuration;
}
/**
* 用于创建代理对象
* @param daoInterfaceClass
* @param <T>
* @return
*/
//实现代理对象和类加载器
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return null;
}
/**
* 释放资源
*/
@Override
public void close() {}
}
实现SqlSession
至于为什么把实现SqlSession单独列出来讲呢。个人感觉SqlSession是最重要也是最难理解的部分。小结一下上面的东西,不过就是用工具类XMLConfigBuilder解析出配置文件和Mapper文件,然后存储到Configuration中,然后再在Configuration中创建一个Mapper对象存储与数据库交互的相关信息。然后那几个SqlSessionFactoryBuiler和SqlSessionFactory不过就是为了创建SqlSession的工厂模式(不断传递得到的Configurarion)。
到了SqlSession,首先要实现getMapper方法
回顾一下我们平时使用mybatis的时候,调用dao层接口的时候,getMapper方法的参数都是一个“xxx.class”。这里mybatis在底层用的是动态代理。
所以在我们自己实现的SqlSession中
/**
* 用于创建代理对象
* @param daoInterfaceClass
* @param <T>
* @return
*/
//实现代理对象和类加载器
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},
new MapperProxy(configuration));
}
众所周知实现动态代理的方式,调用newProxyInstance(),第一个参数传入类加载器(谁调用,就用谁的类加载器,所以这里用传入的daoInterfaceClass),第二个参数Class数组,第三个参数InvocationHandler接口类型(接口的实现类)。所以前两个我们都有,所以再创建一个实现InvocationHandler的实现类MapperProxy
public class MapperProxy implements InvocationHandler {
//key全限定类型和方法名
private Map<String, Mapper> mappers;
public MapperProxy(Map<String, Mapper> mappers, Connection conn) {
this.mappers = mappers;
}
/**
* 用于对方法进行增强,即调用selectList方法
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//1.获取方法名
String methodName = method.getName();
//2.获取全限定类名
String className = method.getDeclaringClass().getName();
//3.组合key值,取出mapper
String key = className+"."+methodName;
//4.获取mappers中的Mapper对象
Mapper mapper = mappers.get(key);
// System.out.println(mapper.getQuerySql());
//5.判断是否有Mapper
if(mapper == null){
throw new IllegalArgumentException("mapper为空");
}
return new Executor().selectList(mapper);
}
}
在MapperProxy中实现接口的invoke方法,在invoke中实现dao层中的方法,说白了就是实现需要去执行的sql语句。于是调用Executor工具类(Executor是处理jdbc的类,即获取数据库连接,根据sql语句去数据库中查询,然后封装返回结果集,就是jdbc的那一套)
/**
* 负责执行SQL语句,并且封装结果集
*/
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
//1.取出mapper中的数据
String queryString = mapper.getQuerySql();//select * from user
String resultType = mapper.getResultType();//com.itheima.domain.User
Class domainClass = Class.forName(resultType);
//2.获取PreparedStatement对象
pstm = conn.prepareStatement(queryString);
//3.执行SQL语句,获取结果集
rs = pstm.executeQuery();
//4.封装结果集
List<E> list = new ArrayList<E>();//定义返回值
while(rs.next()) {
//实例化要封装的实体类对象
E obj = (E)domainClass.newInstance();
//取出结果集的元信息:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//取出总列数
int columnCount = rsmd.getColumnCount();
//遍历总列数
for (int i = 1; i <= columnCount; i++) {
//获取每列的名称,列名的序号是从1开始的
String columnName = rsmd.getColumnName(i);
//根据得到列名,获取每列的值
Object columnValue = rs.getObject(columnName);
//给obj赋值:使用Java内省机制(借助PropertyDescriptor实现属性的封装)
PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);//要求:实体类的属性和数据库表的列名保持一种
//获取它的写入方法
Method writeMethod = pd.getWriteMethod();
//把获取的列的值,给对象赋值
writeMethod.invoke(obj,columnValue);
}
//把赋好值的对象加入到集合中
list.add(obj);
}
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
release(pstm,rs);
}
}
private void release(PreparedStatement pstm,ResultSet rs){
if(rs != null){
try {
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(pstm != null){
try {
pstm.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
这里出现一个问题了,Executor中的selectList()方法两个参数,一个是Mapper。还记得Mapper中存储什么嘛?(sql语句和返回结果的全限定类名),第二个是conn,就是DriverManager的那个注册连接。
回想一下jdbc的时候如何拿到连接的呢。需要url,driver,username,password。那么这些信息在哪呢?
在Configuration中,我们解析mybatis配置文件的时候不就刚好把数据源的信息封装到Configuration中了嘛。所以回溯到SqlSession中,在SqlSession还要创建出一个Connection对象。
继续完善SqlSession中的代码
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
private Connection conn;
public DefaultSqlSession(Configuration configuration){
this.configuration = configuration;
this.conn = DataSourceUtil.getConnection(configuration);
}
/**
* 用于创建代理对象
* @param daoInterfaceClass
* @param <T>
* @return
*/
//实现代理对象和类加载器
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},
new MapperProxy(configuration.getMappers(),conn));
}
/**
* 释放资源
*/
@Override
public void close() {
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
为了体现“面向对象”性,创建一个新的工具类DataSourceUtil,专门处理获得连接的操作
public class DataSourceUtil {
public static Connection getConnection(Configuration configuration) {
try{
Class.forName(configuration.getDriver());
return DriverManager.getConnection(configuration.getUrl(),configuration.getUsername(),configuration.getPassword());
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
ok,至此,我们所有的方法就都实现完了。
在测试类中测试一下手动实现的mybatis
public class mybatisTest {
public static void main(String[] args) throws IOException {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
SqlSession session = factory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
List<User> users = userDao.findAll();
for (User user:users
) {
System.out.println(user.toString());
}
session.close();
in.close();
}
}
结果是成功的。
粘贴一下文件的目录,如果想自己也试试的同学们可以简单参考一下