2.自定义Mybatis的方式(不推荐)了解即可

1.user实体类

package com.itheima.domain;

import java.util.Date;

public class User {
    /*根据ORM的思想:实体类和数据库的字段名要对应*/
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

2.IUserDao接口

package com.itheima.dao;

import com.itheima.domain.User;
import com.itheima.mybatis.annotation.Select;
/*import org.apache.ibatis.annotations.Select;*/

import java.util.List;

public interface IUserDao {
    //查询所有
    //使用注解的好处:不用特意的写入结果集,配置id,注解一步搞定
    /*@Select("select * from user")*/
    //配置文件的方式
    /*List<User> findAll();*/
    /*使用注解的方式*/
    @Select("select * from user")
    List<User> findAll();
}

3.配置mybatis(执行Sql语句的注释 select)

package com.itheima.mybatis.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*使用注解的方式执行*/
//改变注解的生命周期
@Retention(RetentionPolicy.RUNTIME)
//改变注解的出现位置
@Target(ElementType.METHOD)
public @interface Select {
/*
配置SQL语句
 */
String value();
}

4.配置mybatis(执行数据库的配置 Configuration)

package com.itheima.mybatis.cfg;

import java.util.HashMap;
import java.util.Map;

/*
* 自定义mybatis的配置类
* */
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<String, Mapper> mappers) {
        //this.mappers = mappers;只能赋值,一个一个替换
        //但是结果有可能是多个,所以
        this.mappers.putAll(mappers);//此处需要采用追加的方式
        //然后此时需要new出来,然后选择new HashMap<String, Mapper>();否则空指针异常
    }

    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;
    }

}

5.配置mybatis(执行Mapper的资源引入 Mapper)

package com.itheima.mybatis.cfg;

/*
* 自定义:Mapper代替xml中的mapper映射路径配置化:
*   用于封装执行的SQL语句和结果类型的全限定类名
* */
public class Mapper {
    private String queryString;//SQL
    private String resultType;//实体类的全限定类名

    public String getQueryString() {
        return queryString;
    }

    public void setQueryString(String queryString) {
        this.queryString = queryString;
    }

    public String getResultType() {
        return resultType;
    }

    public void setResultType(String resultType) {
        this.resultType = resultType;
    }
}

6.配置Resource(执行Resource的资源引入接口的映射文件)

package com.itheima.mybatis.io;

import java.io.InputStream;

/*
* 使用类加载器读取配置文件的类
* */
public class Resources {
    /*
    * 根据传入的参数,获取一个字节输入流
    *   1.获取这个类的字节码.获取这个类中的类加载器.根据类加载器来读取这个配置
    * */
    public static InputStream getResourceAsStream(String filePath){
        return Resources.class.getClassLoader().getResourceAsStream(filePath);
    }
}

7.配置mybatis(执行sqlsession的创建 DefaultSqlSessionFactory)

package com.itheima.mybatis.sqlsession.defaults;

import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.SqlSessionFactory;

/*
* 创建工厂接口的实现类
* */
public class DefaultSqlSessionFactoryImpl implements SqlSessionFactory {
    //从SqlSessionFactoryBuilder传来的cfg,在这使用构造函数
    private Configuration cfg;

    public DefaultSqlSessionFactoryImpl(Configuration cfg){
        this.cfg=cfg;
    }

    //用于创建一个新的操作数据库对象
    public SqlSession openSession() {
        /*传到DefaultSqlSessionImpl中去,有逐层传递的意思在*/
        return new DefaultSqlSessionImpl(cfg);
    }
    /*
    * 总结:我们使用工厂创建对象,先把工厂的构建者联系起来,这样的话构建者就会构建工厂,
    * 然后工厂生产SqlSession,最后SqlSession将会创建代理对象/释放资源等其他操作(接口使用实现类使用)。
    * */
    /*
    * 总体的流程:先从io里面通过设置Resource类,读取到配置文件出来的流【也就是读取到流中的信息,这些信息就是我们要的】,
    * 然后交给工厂的构建者————构建者使用工具类————给我们构建了一个工厂对象————工厂对象里面的对象给我们提供了一个OpenSession————
    * 然后这个OpenSession给我们提供了一个session方法,然后现在他是接口,我们通过实现类来实现对应的方法即可————例如:查询所有、动态代理等其他操作
    * */
}

8.配置mybatis(执行sqlsession的创建 DefaultSqlSession)

package com.itheima.mybatis.sqlsession.defaults;


import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.proxy.MapperProxy;
import com.itheima.mybatis.util.DataSourceUtil;

import javax.sql.DataSource;
import java.lang.reflect.Proxy;
import java.sql.Connection;

/*
* SqlSession接口的实现类
* */
public class DefaultSqlSessionImpl implements SqlSession {

    /*传入cfg并且,接收cfg*/
    private Configuration cfg;
    //
    private Connection connection;
    /*构造函数:当程序开始的时候就在创建*/
    public DefaultSqlSessionImpl (Configuration cfg){
        this.cfg = cfg;
        connection = DataSourceUtil.getConnection(cfg);
    }

    /*
    * 用于创建代理对象
    * */
    public <T> T getMapper(Class<T> daoInterfaceClass) {
        /*参数:(类加载器,这个类的相同的接口,自己的代理方式)*/
        //代理:你代理谁,你就使用谁的类加载器
        //这个类的相同的接口(本身是接口就传入本身即可)
        //自己的代理方式
        //cfg.getMappers())获取的sql语句
        Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
                new Class[]{daoInterfaceClass},new MapperProxy(cfg.getMappers(),connection));
        return null;
    }
    /*
    * 用于释放资源
    * */
    public void close() {
        if (connection == null) {
            try {
                connection.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

9.配置mybatis(执行sqlsession的创建代理MapperProxy)

package com.itheima.mybatis.sqlsession.proxy;

import com.itheima.mybatis.cfg.Mapper;
import com.itheima.mybatis.util.Executor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;


public class MapperProxy implements InvocationHandler {
    //Map的key是全限定类名+方法名
    private Map<String, Mapper> mappers;
    //第二个连接的参数
    private Connection conn;
    //使用构造函数并且传进去
    public  MapperProxy(Map<String,Mapper> mappers, Connection conn){
        this.mappers = mappers;
        this.conn = conn;
    }
    //用于对方法进行增强的,我们的增强其实就是调用selectList方法
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //1.获取方法名
        String methodName = method.getName();
        //2.获取全限定类名(获取方法所在类的名称)
        String className = method.getDeclaringClass().getName();
        //3.组合key
        String key = className+"."+methodName;
        //4.获取mappers中的Mapper对象
        Mapper mapper = mappers.get(key);
        //5.判读是否有mapper
        if (mapper == null) {
            //抛出停止程序的异常(RuntimeException的)
            throw new IllegalArgumentException("传入的参数有误");
        }
        //6.使用工具类执行查询所有

        return new Executor().selectList(mapper,conn);
    }
}

10.配置mybatis(执行sqlsession的创建 SqlSessionFactory接口)

package com.itheima.mybatis.sqlsession;

/*SqlSessionFactory接口
* 实现主控制类的接口1,
* */
public interface SqlSessionFactory {
    /*
    * 用于打开一个新的SqlSession对象
    * */
    SqlSession openSession();
}

11.配置mybatis(执行sqlsession的创建SqlSession接口)

package com.itheima.mybatis.sqlsession;

/*
* 自定义Mybatis中数据库交互的核心类
* 它里面可创建dao接口的代理对象
* 实现主控制类的接口1 SqlSessionFactory 中的接口2 SqlSession
* */
public interface SqlSession {
    /*
    * 根据参数创建一个动态代理对象
    * daoInterfaceClass dao的接口字节码
    * */

    /*什么是接口字节码或者接口类?又有什么区别*/
    <T> T getMapper(Class<T> daoInterfaceClass);
    //释放资源
    void close();


}

12.配置mybatis(执行sqlsession的创建SqlSessionFactoryBuilder构建者)

package com.itheima.mybatis.sqlsession;

import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.defaults.DefaultSqlSessionFactoryImpl;
import com.itheima.mybatis.util.XMLConfigBuilder;

import java.io.InputStream;

/*
* 创建一个SqlSessionFactory对象
*   主控制类
*
* 根据参数的字节流来构建一个SqlSessionFactory工厂
* */
public class SqlSessionFactoryBuilder {
    public SqlSessionFactory build(InputStream config){
        Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
        return new DefaultSqlSessionFactoryImpl(cfg);
    }
}

 

13.配置mybatis(使用工具类util 获取连接池的连接DataSourceUtil )

package com.itheima.mybatis.util;

import com.itheima.mybatis.cfg.Configuration;

import java.sql.Connection;
import java.sql.DriverManager;
/*
* 用于创建数据源的工具类
* */
public class DataSourceUtil {
    /**
     * 用于获取一个连接
     * @param cfg
     * @return
     */
    public static Connection getConnection(Configuration cfg){
        try {
            Class.forName(cfg.getDriver());
            return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

}

14.配置mybatis(使用工具类util 执行Sql语句 )

package com.itheima.mybatis.util;

import com.itheima.mybatis.cfg.Mapper;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/*
* 执行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.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();
            }
        }
    }
}

15.配置mybatis(使用工具类util 获取xml的值)

package com.itheima.mybatis.util;

import com.itheima.mybatis.annotation.Select;
import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.cfg.Mapper;
import com.itheima.mybatis.io.Resources;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
* 自定义配置连接数据库==自定义实现连接配置文件中的内容并且使用
* */
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/IUserDao.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 = Resources.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.setQueryString(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;
    }

}

---以上可以直接通过一个依赖来解决---

17.IUserDao.xml接口配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--配置映射-->
<mapper namespace="com.itheima.dao.IUserDao">
    <!--配置查询所有 id必须写这个类中的方法名否则不生效

        resultType:查询所有之后类型封装到User的List中【List<User>】-->
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user
    </select>
</mapper>

18.日志log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

19.SqlMapConfig.xml主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--<!DOCTYPE configuration 手动实现,不用通过自动创建的
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">-->

<!--mybatis的主配置文件-->
<configuration>
    <!--配置环境 default默认起什么都可以,但是,下面的id要和默认的一样否则不生效-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源:类型有很多,目前只需讲POOLED-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置文件配置-->
    <!--<mappers>
        <mapper resource="com/itheima/IUserDao.xml"></mapper>
    </mappers>-->
    <!-- resource="com/itheima/IUserDao.xml"  使用xml配置sql语句:指定映射配置文件的位置,映射文件指的是而每个dao的独立的配置文件,是将sql语句独立出来的-->
    <!-- class="com.itheima.dao.IUserDao"     使用注解配置sql语句:-->
    <!--
         指定映射配置文件的位置,映射配置文件指的是每个dao的独立的配置文件
         如果是使用注解的来配置的话,此处应该使用class属性指定被注解的dao全限定类名
     -->
    <!--使用注解的方式来配-->
    <mappers>
        <mapper class="com.itheima.dao.IUserDao"></mapper>
    </mappers>
</configuration>

20.测试类

package com.itheima;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import com.itheima.mybatis.io.Resources;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.SqlSessionFactory;
import com.itheima.mybatis.sqlsession.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    /*mybatis入门案例*/
    public static void main(String[] args) throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂:创建dao对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);//(这里的SqlSessionFactory是一个接口,得通过实现创建一个对象来使用)
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象(目的:不改变原码的方法前提下 对原有的代码进行增强)
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user:users){
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
        //思路:通过读取配置文件来准备一个工厂,
        // 这个工厂将会生产出一个对象
        // 这个对象用于对dao的实现,有了这个dao的实现
        //我们就使用dao.执行查询所有的

    }
    /*
    * 这个小实战的项目目的:
    *       通过根据测试类中缺少的来创建类和接口
    *       取消了依赖:取消了mybatis帮我们配置,
    * 通过自己写实现类和接口来创建:(麻烦的,但是老师想让我们理解动态代理的思想)
    *
    * */
    /*
    * 整体总结:我们需要实现查询所有的功能,并且这个功能在工具类中,我们需要调用这个工具类,什么时候调用
    * 就是在实现dao增强的时候调用的这个工具类,那什么时候创建dao的实现类(代理对象的增强)DefaultSqlSessionImpl?
    * 我们可以从MapperProxy中找到执行的语句和封装的结果,从配置文件中来找,然后交给XMLConfigBuilder这个工具类来读取配置文件的信息(通过流的方式)
    * 读取到之后需要存起来,这时候我们就使用到了Configuration对象来存放读取xml到的信息并且使用。
    *最后还有归于两件事:
    *   1.创建代理对象
    *   2.实现查询所有
    * */
}

21.依赖

 <dependencies>
        <!--添加mybatis依赖-->
        <!--<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        自定义配置mybatis好多
        -->
        <!--连接数据库依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--添加日志的依赖-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!--单元测试的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>
    </dependencies>

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值