第一步,读取配置信息
流程:SqlSessionFactoryBuilder 接受sqlMapConfig.xml信息,构建sqlsessionfactory对象。
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
分析:
1…Resources实现:根据类加载器获取文件路径,一般项目中不用相对路径和绝对路径。
public class Resources {
public static InputStream getResourceAsStream(String filepath){
return Resources.class.getClassLoader().getResourceAsStream(filepath);
}
}
2.SqlSessionFactoryBuilder 实现:创建SqlSessionfactory,通过XMLConfigBuilder.loadConfiguration()方法解析sqlmapconfig的配置信息cfg,将信息传递给Sqlsessionfactory。
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream config) {
Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
return new SqlSessioFactoryImpl(cfg);
}
}
【1】:Configuration 封装了数据库的连接信息和映射文件的配置,映射文件用一个map保存,key为映射文件中的mapper的namespace和select的id,value为select的resulttype和select中的sql语句。value用一个mappr来封装。
configuration实现:
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String,Mapper> mappers = new HashMap<>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.SqlSessionFactoryImpl实现:openSession创建sqlsession,并将cfg传递给sqlsession。
public class SqlSessioFactoryImpl implements SqlSessionFactory{
private Configuration cfg;
public SqlSessioFactoryImpl(Configuration cfg) {
this.cfg = cfg;
}
@Override
public SqlSession openSession() {
return new SqlSessionImpl(cfg);
}
}
第二步,产生真正操作数据库的sqlSession对象。
流程:
SqlSession session = factory.openSession();
分析:
sessionImpl实现:获取cfg和数据库连接conn,创建真正的sqlSession。
【1】DataSourceUtils:连接数据库工具
public class SqlSessionImpl implements SqlSession{
private Configuration cfg ;
private Connection conn;
public SqlSessionImpl(Configuration cfg) {
this.cfg = cfg;
this.conn = DataSourceUtils.getConnection(cfg);
}
}
第三步,生成接口代理对象
流程:
UserDao userDao = session.getMapper(UserDao.class);
分析:
1.getMapper():创建代理对象
【1】代理对象实现:
实现了InvocationHandler接口,根据key找到map中对应value。将value传递给Executor()的selectList()方法中。
public class MapperProxy implements InvocationHandler{
private Map<String,Mapper> mappers;
private Connection conn;
public MapperProxy(Map<String, Mapper> mappers,Connection conn) {
this.mappers = mappers;
this.conn = conn;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodname = method.getName();
String classname = method.getDeclaringClass().getName();
String key = classname+"."+methodname;
Mapper mapper = mappers.get(key);
if(mapper == null){
throw new IllegalArgumentException("传入的参数有误");
}
return new Executor().selectList(mapper,conn);
}
}
2.close():关闭流资源。
public class SqlSessionImpl implements SqlSession{
private Configuration cfg ;
private Connection conn;
public SqlSessionImpl(Configuration cfg) {
this.cfg = cfg;
this.conn = DataSourceUtils.getConnection(cfg);
}
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},
new MapperProxy(cfg.getMappers(),conn));
}
@Override
public void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
第四步,执行dao方法,获取结果集。
流程:
List<User> users = userDao.findAll();
for (User user:users) {
System.out.println(user);
}
分析:
userDao.findAll():代理对象调用方法,获取方法名,和类的全限定类名组成map的key。
Executor().selectList():根据key传过来的map的value,执行指定的sql语句和封装到指定的结果集中(根据map中的resultType反射出结果集封装到那个类中)。
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
//1.取出mapper中的数据
String queryString = mapper.getQueryString();//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();
}
}
}
}