mybatis造轮子(持续更新中)

本文详细介绍了MyBatis的配置过程,包括pom.xml中的依赖引入,持久层配置文件的命名与位置,以及sqlMapConfig.xml的设置,如二级缓存、日志配置等。同时展示了log4j.properties的日志配置和测试类的编写,涵盖了懒加载、一级缓存和二级缓存的测试用例。
摘要由CSDN通过智能技术生成

mybatis必要xml的配置

pom.xml中的配置(引入依赖)

    <dependencies>
        <!-- mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- log4j 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!-- 测试jar-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
		<!--配置分页  放在最下面-->
	    <dependency>
	      	<groupId>com.github.pagehelper</groupId>
	     	<artifactId>pagehelper</artifactId>
	      	<version>4.1.4</version>
    	</dependency>
 	

    </dependencies>
持久层配置文件

1.配置文件的名称必须以 接口名+.xml命名(如IStudentDao.xml)
2.文件的位置必须放在main目录下resources\com\w\dao对应目录

<?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.w.dao.IStudentDao">

    <!--配置缓存
        1.开启  <cache></cache>
        2.配置参数  flushInterval="10000" 配置缓存刷新时间 清空
                     eviction="LRU" 最少使用的先删除  就是使用 LruCache 类实现
                     size="1000"  缓存最多 1000 条数据 1000 sql
                     readOnly="true" 只读不可修改 只读性能差,但是安全 获取的拷贝   可以修改 获取的缓存对象就是直接的应用
                     blocking="false" 配置是否阻塞
                     type 用来配自定义二级缓存
    -->
    <cache flushInterval="10000" eviction="LRU" size="1000" readOnly="false" blocking="false" ></cache>
        <!--配置查询所有学生的 方法
            id:为对应的方法方法名
            resultType:返回数据类型的全限定名
        -->
        <select id="findAllStudent" resultType="com.w.entity.Student">
            select * from student_tb
        </select>
</mapper>
配置文件的编写

在resources下创建配置文件mysql.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/111
jdbc.username=root
jdbc.password=123456
然后创建sqlMapConfig.xml

在resources下创建配置文件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">

<configuration>

    <!-- 声明配置文件路径 -->
    <properties resource="mysql.properties"></properties>

    <!--
    开启驼峰写法   自动将数据库表字段 s_address 映射为 sAddress
     <setting name="mapUnderscoreToCamelCase" value="true"/>
    -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>

        <!-- 开启全局懒加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>

        <!--解决 懒加载时 打印对象toString 触发 懒加载
          lazyLoadTriggerMethods:指定哪个对象的方法触发一次延迟加载。默认值:equals,clone,hashCode,toString
      -->
        <setting name="lazyLoadTriggerMethods" value="false"/>


        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>

    </settings>



    <!--配置别名-->
    <typeAliases>
        <package name="com.w.entity"/>
    </typeAliases>

    <plugins>

        <!-- 让mybatis  加载PageHelper -->
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 使用MySQL方言的分页 -->
            <property name="helperDialect" value="mysql"/><!--如果使用mysql,这里value为mysql-->
            <property name="pageSizeZero" value="true"/>
        </plugin>

    </plugins>

    <!-- 选区mysql 环境-->
    <environments default="mysql">
        <!-- mybtis 环境 -->
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接池数据源-->
            <dataSource type="POOLED">
                <!-- 通过配置文件初始化参数 -->
                <property name="driver" value="${jdbc.driver}"/>
                <!-- 配置url-->
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>



    <mappers>
        <!-- 告诉mybatis 要根据IStudentDao.xml 的业务创建一个对应的实现类  -->
       <!-- <mapper resource="com/w/dao/IStudentDao.xml"></mapper>-->

        <!-- 也是告诉 mybtis 创建 一个IStudentDao 实现类,并且业务按照IStudentDao.xml-->
       <!-- <mapper class="com.w.dao.IStudentDao"></mapper>-->

        <!--告诉mybatis com.w.dao所有的接口都要 创建对应的实现类对象 -->
        <package name="com.w.dao"/>

    </mappers>

</configuration>
配置日志(log4j)

配置mybatis的日志,在resouces目录下创建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=mybatis.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
  
测试类

junit测试

public class MyBatis2 {

    SqlSessionFactory sqlSessionFactory = null;
    SqlSession sqlSession = null;
    StudentDao studentDao = null;
    StudentDao studentDao2 = null;
    ScoreDao scoreDao = null;
    @Before// 在@Test 之前执行 初始化资源
    public void init() throws IOException {
        //1获取连接
        InputStream inputStream  = Resources.getResourceAsStream("mybatisConfig.xml");

        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 获取连接工厂
         sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

        // 获取 sqlSession  mysql连接
        // 默认情况 关闭自动提交-----------》开启事务
        sqlSession = sqlSessionFactory.openSession(true);

        studentDao = sqlSession.getMapper(StudentDao.class);
        scoreDao = sqlSession.getMapper(ScoreDao.class);
    }

    @Test  // 一对多懒加载
    public void  findAllStudentWithScoreLazyTest(){


        List<Student> studentList =   studentDao.findAllStudentWithScoreLazy();

        for (Student student:studentList){
            System.out.println("student-name:"+student.getName());
            // 懒加载 只有当调用时 student.getScoreList() 才去请求查询学生成绩
            System.out.println("student-scoreList:"+student.getScoreList());

            // 一旦调用 student的 toString 就会触发懒加载
            //mybatis 底层机制只要 触发equals,clone,hashCode,toString 就会懒加载
            // 可以再setting 里面关闭功能
            System.out.println("student:"+student);
        }

    }


    @Test //测试方法必须时 public void
    public void findAllScoreWithStudentByLazyTest(){

       List<Score> scoreList =  scoreDao.findAllScoreWithStudentByLazy();

       for (Score score:scoreList){

           // 打印对象没有触发懒加载是因为再setting 已经关闭
           System.out.println("score:"+score.getCouresename());

           // 获取student 相关信息 触发懒加载
//           System.out.println("student:"+score.getStudent());
       }

    }
    /**
     * 一级缓存
     */
    @Test
    public void firstLevelCacheTest(){
        //查询所有时 可以缓存数据,但是一旦发生增加 或者删除 修改 就要清空
        studentDao.findAllStudentWithScoreLazy();


        // 查询第一次  有执行sqlselect * from student_tb where id = ?
        Student student1 =    studentDao.findStudentById(4);
        System.out.println("student1:"+student1);

        // 查询第二次  没有执行sql 没有去数据库查数据,从一级缓存sqlsession 获得数据
        Student student2 =    studentDao.findStudentById(4);
        System.out.println("student2:"+student2);

        student2.setName("志恒哥1");
        int num = studentDao.updateStudent(student2);
        System.out.println("num:"+num);

        // 再次查询数据 需要去数据库查数据 为什么?
        // 应为 当前sqlSession 发生 修改,增加,删除 动作,就会把当前缓存的所有 数据清空
        Student student3 =    studentDao.findStudentById(4);
        System.out.println("student3:"+student3);

        studentDao.findAllStudentWithScoreLazy();

    }


    @Test  // 二级缓存
    public void secondLevelCacheTest(){

        // 查询第一次  有执行sqlselect * from student_tb where id = ?
        Student student1 =    studentDao.findStudentById(4);
        System.out.println("student1:"+student1);

        // 查询第二次  没有执行sql 没有去数据库查数据,从一级缓存sqlsession 获得数据
        Student student2 =    studentDao.findStudentById(4);
        System.out.println("student2:"+student2);

        // 只有sqlSession 调用close(),commit() 方法 才会将数据提交到二级换存,其他的sqlSession才能拿到
//        sqlSession.close();
        sqlSession.commit();

        // studentDao2   studentDao 来自于不同的sqlSession
        studentDao2 = sqlSessionFactory.openSession(true).getMapper(StudentDao.class);

        Student student3 = studentDao2.findStudentById(4);
        System.out.println("student3:"+student3);
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值