SSM-MyBatis

单体框架-SSM在项目中所代替的部分(mybatis-->dao层)
    

框架的概念:jar+配置文件
    

发展历程
    MyBatis原名是iBatis,是Apache的开源项目。2010.6月跟随开发团队投入Google  code旗下。在IBatis3.x正式更名为MyBatis。它提供了持久层架包包括SQL Maps和DATA Access Object(DAO);

安装(我没用,直接maven)
    网址:https://github.com/mybatis/mybatis-3

Mybatis特性
    MyBatis支持定制化SQL、存储过程以及高级映射
    MyBatis避免了几乎所有的JDBC代码和手动设置参数以及结果集解析操作
    MyBatis可以使用简单的XML或注解实现配置和原始映射;将接口和Java的POJO(Plain Ordinary Java Object,普通的Java对象)映射成数据库中的记录
    Mybatis是一个半自动的ORM(Object   Relation  Mapping)框架

与其他持久层的技术对比
    jdbc(唯一连接方式)但是耦合度高,开发效率低,不利于开发(所以要进行保证)
    Hibernate和JPA:操作简单,但是复杂查询不足
    MyBatis:轻量级。sql与java代码分开,效率略逊色于Hibernate

创建MyBatis(Maven(pom创建)版本,因为它一般不会单用,所以我直接写出它最终单用版本)
    1.创建一个普通Maven(方法看我上一次传的)
    2.创建好后,在pom.xml中导入以下代码(这些是maven导入的jar)

<dependencies>
    <!-- Mybatis核心 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>

    <!-- junit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.17</version>
    </dependency>

    <!-- log4j日志 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>


    3.在resource文件夹中创建一个新文件(mybatis-config.xml)
    4.在新创的文件mybatis-config.xml中加入mybatis的API中的getting started(新手入门)中关于mybatis-config.xml的内容(加以修改数据源--->jdbc是连接数据库唯一的方式)
  

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/curd?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

 5.在resources文件夹下创建文件夹mapper,在创建XxxMapper.xml(Xxx--->数据库表名)
 6.在XxxMapper.xml文件下填写如下getting started的内容(修改一些数据,下面具体说)---->我创建的数据库叫curd,表叫user(具体的看源码)

<?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="org.mybatis.example.BlogMapper"> 
 <select id="selectUser" resultType="User"> 
 select * from user where id = #{id} 
 </select> 
</mapper> 


    7.创建接口和实体类
    8.创建测试类
    链接:https://pan.baidu.com/s/1Fq0qdRkjY4l69luLwR-xPA
    提取码:0303

MyBatis核心配置文件
 核心文件configuration有严格的顺序要求:(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)  

<?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文件,此时就可以${属性名}的方式访问属性值-->
    <properties resource="jdbc.properties"></properties>
    <settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>

          <!--
        typeAliases:设置类型别名
    -->
    <typeAliases>
        <!--
            typeAlias:设置某个具体的类型的别名
            属性:
            type:需要设置别名的类型的全类名
            alias:设置此类型的别名,若不设置此属性,该类型拥有默认的别名,即类名且不区分大小写
            若设置此属性,此时该类型的别名只能使用alias所设置的值
        -->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User"></typeAlias>-->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User" alias="abc"></typeAlias>-->
        <!--以包为单位,设置改包下所有的类型都拥有默认的别名,即类名且不区分大小写-->
        <package name="com.atguigu.mybatis.bean"/>
    </typeAliases>

<!--    分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    <!--
        environments:设置多个连接数据库的环境
        属性:
        default:设置默认使用的环境的id
    -->
    <environments default="mysql_test">
        <!--
            environment:设置具体的连接数据库的环境信息
            属性:
            id:设置环境的唯一标识,可通过environments标签中的default设置某一个环境的id,表示默认使用的环境
        -->
        <environment id="mysql_test">
            <!--
                transactionManager:设置事务管理方式
                属性:
                type:设置事务管理方式,type="JDBC|MANAGED"
                type="JDBC":设置当前环境的事务管理都必须手动处理
                type="MANAGED":设置事务被管理,例如spring中的AOP
            -->
            <transactionManager type="JDBC"/>
            <!--
                dataSource:设置数据源
                属性:
                type:设置数据源的类型,type="POOLED|UNPOOLED|JNDI"
                type="POOLED":使用数据库连接池,即会将创建的连接进行缓存,下次使用可以从缓存中直接获取,不需要重新创建
                type="UNPOOLED":不使用数据库连接池,即每次使用连接都需要重新创建
                type="JNDI":调用上下文中的数据源
            -->
            <dataSource type="POOLED">
                <!--设置驱动类的全类名-->
                <property name="driver" value="${jdbc.driver}"/>
                <!--设置连接数据库的连接地址-->
                <property name="url" value="${jdbc.url}"/>
                <!--设置连接数据库的用户名-->
                <property name="username" value="${jdbc.username}"/>
                <!--设置连接数据库的密码-->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
        <environment id="mysql_development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

MyBatis获取参数的两种方式
    获得方式为:${}  和 #{}
    方法的本质:${}---->字符串的拼接;#{}---->占位符的复制
    优缺点:${}凭借字符串或日期的时候,需要手动加单引号(等一下可以看事例);#{}则会自动添加
    当参数数量不同的时候,实例分析:
        1.当只有一个字面量(八大基本类型+对应的包装类+string)参数的时候
        两种都可以用,里面的参数可以为任意字符串,但是${}里面不能为纯数字或以数字开头的字符串,因为它本身具有运算效果

<!--    User getByName(String username);-->
    <select id="getByName" resultType="com.baby.bean.User">
        select * from user where username='${s1}'
--             select * from user where username=#{12}
    </select>


        2.当有多个字面量参数的时候
        多个参数的时候,它会自动存在一个map集合中,key只有arg和param两种。注意:arg是从0开始,param是从一开始,他们不能超过参数的数目

<!--    User getBys(String username,String role,String pass);-->
    <select id="getBys" resultType="com.baby.bean.User">
--          select * from user where username='${arg0}' and role='${arg1}' and pass='${arg2}'
   select * from user where username=#{param1} and role=#{param2} and pass=#{param3}
    </select>


        3.当有多个字面量参数的时候,可以自定义一个map集合存储
        我们需要手动创建一个map集合,然后复制,key的值为我们自定义的值

<!--    User getByss(Map<String,String> map);-->
    <select id="getByss" resultType="com.baby.bean.User">
--           select * from user where username=#{name} and role=#{role} and pass=#{pass}
    select * from user where username='${name}' and role='${role}' and pass='${pass}'
    </select>


        4.当参数是一个对象的时候
        我们可以直接写对应JavaBean的成员变量名

    <insert id="getByUser">
--         INSERT INTO USER  VALUES( NULL,'${username}','${role}','${pass}')
     INSERT INTO USER  VALUES( NULL,#{username},#{role},#{pass})
    </insert>


        5.当参数添加注解的时候
        我们可以在接口中为参数添加注解,注解里面的字面量可以为key值;param1,param2也可以作为key值

<!--
@paran里面只有一个值的时候
@param(value="")===@param("")
 User checkUser(@Param(value = "username") String username,@Param("password") String pass);
-->
<select id="checkUser" resultType="user">
    <!--select * from user where username='${username}' and pass='${password}'-->
    select * from user where username=#{param1} and pass=#{param2}
</select>


        6.当参数为对象加注解的时候
        这时候只可以使用 语法:--->注解的值.bean的成员名

<!--  int getInstallById(@Param("user") User user);-->
<insert id="getInstallById">
    <!--INSERT INTO USER  VALUES( NULL,'${user.username}','${user.role}','${user.pass}')-->
    INSERT INTO USER  VALUES( NULL,#{user.username},#{user.role},#{user.pass})
</insert>

MyBatis的查询情况(5)
    resultType和resultMap两种返回结果集
    resultType--->1.真实的类(全类名) 2.类的别名(自定义的别名和默认别名(八大基本类型及对应的包装类))
    resultMap--->自定义映射;值为自己定义一个resultMap的id(主要可以解决数据库字段名和实体类的属性名不一致的问题)
    1.查询返回一个实体类
    

<!-- User selectById(@Param("id") int id);-->
<select id="selectById" resultType="User">
    select * from user where id=#{id}
</select>


    2.查询返回一个list集合
    如果返回值为list集合 返回结果映射为<>泛型里面的值

<!--   List<User> selectAll(); -->
<select id="selectAll" resultType="user">
     select * from user
</select>


    3.查询返回一个数据
    这是根据字段名并不是字段值查询的,所以是string类型而不是int类型

<!--   int selectCount(@Param("id") String name);-->
<select id="selectCount" resultType="int">
    SELECT COUNT(#{id}) FROM USER
</select>


    查询返回一条数据返回为map集合(唯一的好处可以不需要创建bean,可以当临时变量的存储)

<!--Map<String,Object> selectAllToMap(@Param("id") int id);  -->
<select id="selectAllToMap" resultType="map">
    select * from user where id=#{id}
</select>
结果:{role=辅助, id=3, username=瑶}


    
    查询多条数据返回为一个map集合(不常用)
    在接口上添加一个注解,字段作为key,value是每天map集合

</select>
<!--
 @MapKey("id")---把"字段"作为key
Map<String,Object> selectAllToMap();
本质:map(map)
  -->
<select id="selectAllToMap" resultType="map">
     select * from user
</select>
结果:
{2={role=射手, pass=123,
 id=2, username=后羿}, 3={role=辅助, id=3, username=瑶}, 
6={role=ly, pass=123, id=6, username=ly},
 7={role=c, id=7, username=c}, 
8={role=ss, id=8, username=ss},
 12={role=sl, pass=123, id=12, username=ls}}

特殊的sql(模糊查询和批量删除及返回主键)
    1.模糊查询
        注意:单引号中如果用#{}获取参数,这时候#{}并不是作为占位符?存在,而是作为字符?号存在,会报错;只能使用concat连接字符串方法

<!--    List<User> getSelectMH(@Param("mh") String mh);-->
<select id="getSelectMH" resultType="user">
    <!--SELECT * FROM USER WHERE username LIKE '%${mh}%'-->
    SELECT * FROM USER WHERE username LIKE concat('%',#{mh},'%')
</select>


    2.批量删除
        批量删除只能用${};当参数为字符串的时候

<!--  int getDelById(String ids);   -->
<delete id="getDelById">
    DELETE  FROM USER WHERE id in (${ids})
</delete>


    3.返回主键
        useGeneratedKeys 取值范围true、false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域型属性中;keyProperty则是指定主键值赋值给哪个字段名

<!--  int getInstallById(@Param("user") User user);-->
<insert id="getInstallById" useGeneratedKeys="true" keyProperty="id">
    <!--INSERT INTO USER  VALUES( NULL,'${user.username}','${user.role}','${user.pass}')-->
    INSERT INTO USER  VALUES( NULL,#{user.username},#{user.role},#{user.pass})
</insert>

自定义映射
    问题:实体类和数据库字段名不一致的时候,不能直接映射赋值?
    解决方案:
        1.在sql语句中取别名

<!--    User selectUser(int id);-->
    <select id="selectUser" resultType="com.baby.bean.User">
     select id,user_name userName,role,pass from user where id = #{id}
     </select>


        2.在mybatis-config配置文件中开启下划线转驼峰(实体类(驼峰)和表的字段名符(_)合对应规则)--->看上面的核心配置文件
        3.自定义映射(resultMap)(可以自己设置值对应,eg:把实体类username的值对应字段名pass,这样username就可以接收pass的值)--->可以只设定与字段名不一致的属性

 <!--
    resultMap:设置自定义映射
    属性:
    id:表示自定义映射的唯一标识
    type:查询的数据要映射的实体类的类型
    子标签:
    id:设置主键的映射关系
    result:设置普通字段的映射关系
    association:设置多对一的映射关系
    collection:设置一对多的映射关系
    属性:
    property:设置映射关系中实体类中的属性名
    column:设置映射关系中表中的字段名
-->
    <resultMap id="id" type="user">
        <id property="id" column="id"></id>
        <result property="userName" column="user_name"></result>
        <result property="role" column="role"></result>
        <result property="pass" column="pass"></result>
    </resultMap>
<!--    User getByName(String username);-->
    <select id="getByName" resultMap="id">
     <!-- select * from user where username=#{16563} -->
        select * from user where user_name='${s1}'
</select>

映射关系(只有查询才有映射关系)(当我们写mapper.xml了 必须写命名空间---><mapper namespace="com.baby.mybatis.mapper.EmpMapper">)

①实体类中映射关系的表示会写在多的一方

②对一用对象表示,对多用集合表示
    多对一映射关系(对象)
        1.级联方式(不太推荐--->可以只写出第二张表的resultMap映射)
        

 <!--type对应的是返回值类型-->
    <resultMap id="deptid" type="com.baby.bean.Emp">
        <id property="eId" column="e_id"></id>
        <result property="eName" column="e_name"></result>
        <result property="eAge" column="e_age"></result>
        <result property="dept.dId" column="d_id"></result>
        <result property="dept.dName" column="d_name"></result>
    </resultMap>
<!--    Emp getSelectEmpAndDeptById(@Param("id") int id);-->
    <select id="getSelectEmpAndDeptById" resultMap="deptid">
        SELECT dept.*,emp.* FROM emp INNER JOIN dept ON emp.`d_id`=dept.`d_id` WHERE emp.`e_id`=#{id}
    </select>


        2.设置多对一的映射关系
        

<!--    Emp getSelectAll();-->
    <resultMap id="allid" type="com.baby.bean.Emp">
        <association property="dept">
            <id property="dId" column="d_id"></id>
            <result property="dName" column="d_name"></result>
        </association>
    </resultMap>
    <select id="getSelectAll" resultMap="allid">
        select  * from emp left join dept on emp.`d_id`=dept.`d_id`
    </select>


        3.分步查询(延时加载,按需加载)
            1.如果想要延迟加载;那么就必须在配置文件中配置mybatis-config--->看核心配置文件

  <settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>


            2.分步查询(如果查getById()那么就不会执行整个方法;但是查询getAll()会执行所有)

<!--
    Emp getById(@Param("id") int id);
    Emp getAll(@Param("id") int id);
-->
   <select id="getById" resultType="com.baby.bean.Dept">
       select * from dept where d_id=#{id}
   </select>
    <resultMap id="did" type="com.baby.bean.Emp">
        <association property="dept" select="com.baby.mapper.WorKMapper.getById" column="d_id">
        </association>
    </resultMap>
    <select id="getAll" resultMap="did">
        select * from emp where e_id=#{id}
    </select>


    一对多关系(集合)
        1.映射关系
            这里必须写完整,不然映射不到

<!--        List<Dept> getDeptToEmpById(@Param("id") int id);-->
    <resultMap id="deptById" type="Dept">
        <id property="dId" column="d_id"></id>
        <result property="dName" column="d_name"></result>
        <collection property="emp" ofType="Emp">
            <id property="eId" column="e_id"></id>
            <result property="eName" column="e_name"></result>
            <result property="eAge" column="e_age"></result>
        </collection>
    </resultMap>
    <select id="getDeptToEmpById" resultMap="deptById">
        SELECT * FROM dept INNER JOIN emp ON emp.`d_id`=dept.`d_id` WHERE dept.`d_id`=#{id}
    </select>


        2.分步查询(获取单个元素可以只执行一条sql语句)
            这里dept 的id映射必须写 不然不能获取

<!--    List<Emp> getDeptDId(@Param("did") int id);-->
        <select id="getDeptDId" resultType="emp">
            select * from emp where d_id=#{did}
        </select> 
 <!--
    分步查询
    Dept getById(@Param("id") int id);
    -->
<resultMap id="did" type="dept">
    <id property="dId" column="d_id"></id>
    <collection property="emp" select="com.baby.mybatis.mapper.EmpMapper.getDeptDId" column="d_id">
    </collection>
</resultMap>
<select id="getById" resultMap="did">
    select  * from dept where d_id=#{id}
</select>

动态(dynamic)SQL语句
    1.if(<if test="userName != '' and userName!=null">)和where(问题:解决多余and和where)
        1.if标签和1=1/2=2恒成立联用--->and是关联字 不可少

<!--
 List<User> getDynamicUser(User user);
 1=1 恒成立=>可以解决没有条件使失去了语句成功运行
   -->
<select id="getDynamicUser" resultType="user">
    select * from user where 1=1
    <if test="userName != '' and userName!=null">
        and user_name like '%${userName}%'
    </if>
    <if test="role != '' and role!=null">
        and role=#{role}
    </if>
    <if test="pass != '' and pass!=null">
        and pass=#{pass}
    </if>
</select>


        2.if和where标签的组合使用(可以省略第一个and;但是我个人不推荐省略)-->where标签可以省略前面的and,但是不能省略表达式后面的and

<!-- List<User> getDynamicUser(User user);-->
<select id="getDynamicUser" resultType="user">
    select * from user
    <where>
        <if test="userName != '' and userName!=null">
            and user_name like '%${userName}%'
        </if>
        <if test="role != '' and role!=null">
            and role=#{role}
        </if>
        <if test="pass != '' and pass!=null">
            and pass=#{pass}
        </if>
    </where>
</select>


    2.trim
        3.trim的可以添加一个或删除一个前缀(后缀)

<!-- List<User> getDynamicUser(User user);-->
<select id="getDynamicUser" resultType="user">
    select * from user
    <!--
    prefix="" :添加一个前缀
    prefixOverrides=""  :删除一个前缀
    suffix=""  :添加一个后缀
    suffixOverrides="" :删除一个后缀
    -->
    <trim prefix="where" suffixOverrides="and">
        <if test="userName != '' and userName!=null">
             user_name like '%${userName}%' and
        </if>
        <if test="role != '' and role!=null">
             role=#{role} and
        </if>
        <if test="pass != '' and pass!=null">
             pass=#{pass}
        </if>
    </trim>
</select>


    3.choose,when和otherwise---->相当于if....if else....else....
        这是单条件,所有不需要加and,而且如果满足任何一个条件,后面的就不会执行;otherwise标签如果前面没有执行的,那么它必定会执行

    <!--    List<User> getById(User user);   -->
<select id="getById" resultType="user">
    select * from user
    <where>
        <choose>
            <when test="userName != '' and userName!=null">
                user_name like '%${userName}%'
            </when>
            <when test="role != '' and role!=null">
                role=#{role}
            </when>
            <otherwise>
                pass=#{pass}
            </otherwise>
        </choose>
    </where>
</select>


        注意:1.insert添加语句必须所有元素一起添加,少一个都不行;2.choose,when,otherwise可以赋值;3.性别必须加单引号(要符合sql规范)

 <!--int installUser(User user); -->
<insert id="installUser">
    INSERT INTO USER  VALUES(
    null,
    <if test="userName != '' and userName!=null">
        #{userName},
    </if>
    <if test="role != '' and role!=null">
        #{role},
    </if>
    <if test="pass != '' and pass!=null">
        #{pass},
    </if>
    <if test="gender != '' and gender !=null">
        <choose>
            <when test="gender==0">'女'</when>
            <when test="gender==1">'男'</when>
            <otherwise>null</otherwise>
        </choose>
    </if>
    )
</insert>


    4.foreach
        如果参数是list集合:foreach属性:①collection(可以填arg0或collection或list三选一)设置循环的数组或集合类型 ②item:表示数组或集合中的一天数据 ③循环体之间的分隔符号

<!--int  insertUsers(List<User> list);-->
<insert id="insertUsers">
    insert into user values
    <foreach collection="list" item="user" separator=",">
        (null,#{user.userName},#{user.role},#{user.pass},#{user.gender})
    </foreach>
</insert>


        如果参数是数组①collection(array,arg0)④open:foreach标签的开始符号;⑤close:foreach的结束符号

<!--    int delUserS(@Param("ids") String its);-->
    <delete id="delUserS">
        delete from user where id in
        <foreach collection="array" item="id" open="("  separator="," close=")">
            '${id}'
        </foreach>
    </delete>


        open和colse不常用

<delete id="delUserS">
    delete from user where
    <foreach collection="arg0" item="id" separator="or">
        id=#{id}
    </foreach>
</delete>


    5.sql
        sql片段,截取公共的片段,通过include来引用(注意写规范,比如‘_’ 和驼峰的别名那些)

<sql id="userAll">
    id,user_name userName,role,pass,gender
</sql>

select <include refid="userAll"></include> from user

MyBatis的缓存--->只针对查询语句有效果
    本质:map集合

    一级缓存
        概述:一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
        存储:以json数据存储
        作用域:一个session会话中
        默认开启
        失效的情况(4种):
            1) 不同的SqlSession对应不同的一级缓存
            2) 同一个SqlSession但是查询条件不同
            3) 同一个SqlSession两次查询期间执行了任何一次增删改操作
            4) 同一个SqlSession两次查询期间手动清空了缓存
    二级缓存
        概念:二级缓存是namespace级别的,即映射文件级别的,不管使用的是哪个SqlSession,只要执行的是该映射文件中的查询语句,结果就会被缓存;此后若再次执行映射文件中相同的查询语句,结果就会从缓存中取
        开启条件:
            a>在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置
            b>在映射文件中设置标签\<cache />
            c>二级缓存必须在SqlSession关闭或提交之后有效
            d>查询的数据所转换的实体类类型必须实现序列化的接口
        二级缓存失效情况:
            两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
            标签种设置flushCache和useCache为false;增删改种只有flushCache,而且默认为false
        <cache />标签的属性
        


     第三方缓存(不常用)
        。。。。。。

MyBatis--逆向工程
    1.引入jar插件

<!-- 控制Maven在构建过程中相关配置 -->
<build>

    <!-- 构建过程中用到的插件 -->
    <plugins>

        <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.0</version>

            <!-- 插件的依赖 -->
            <dependencies>

                <!-- 逆向工程的核心依赖 -->
                <dependency>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-core</artifactId>
                    <version>1.3.2</version>
                </dependency>

                <!-- 数据库连接池 -->
                <dependency>
                    <groupId>com.mchange</groupId>
                    <artifactId>c3p0</artifactId>
                    <version>0.9.2</version>
                </dependency>

                <!-- MySQL驱动 -->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.17</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>


    2.写逆向生成的配置文件--generatorConfig.xml(主要生成(要修改的地址)三个,1.实体类;2.接口;3.接收的映射)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--
            targetRuntime: 执行生成的逆向工程的版本
                    MyBatis3Simple: 生成基本的CRUD(清新简洁版)
                    MyBatis3: 生成带条件的CRUD(奢华尊享版)
     -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/crud?serverTimezone=UTC"
                        userId="root"
                        password="password">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.atguigu.mybatis.entity" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="mapper"  targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.mapper"  targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="login_user" domainObjectName="LoginUser"/>
    </context>
</generatorConfiguration>


    3.生成命令

mybatis--分页插件PageHelper
    1.导入jar包

<!--        分页插件-->
        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>0.9.5</version>
        </dependency>


    2.在核心配置文件配置(注意顺序)--->看核心配置文件

<!--    分页插件-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>


    3.使用并认识分页插件的属性(2个)

①Page<LoginUser> login = PageHelper.startPage(1, 3);
参数:当前页,每一页的记录数
System.out.println(login);
结果属性:Page{count=true, pageNum=1, pageSize=3,
 startRow=0, endRow=3, total=0, 
pages=0, reasonable=null, pageSizeZero=null}

要了解的:pageNum-->当前页  ;  pageSize-->每一页的记录数   ;  
 startROW-->从第几行数据开始   ;  endRow-->第几行结束
total-->总记录数    ;   pages-->页码数


②PageInfo<LoginUser> users =new PageInfo<>(loginUsers,1);
参数:查询的list结果集 ; 逻辑导航分页数
System.out.println(users);
结果属性:PageInfo{pageNum=1, pageSize=3, size=3, startRow=1,
 endRow=3, total=14, pages=5, 
list=Page{count=true, pageNum=1, pageSize=3, startRow=0,
 endRow=3, total=14, pages=5, reasonable=false, pageSizeZero=false}, 
prePage=0, nextPage=2, isFirstPage=true, 
isLastPage=false, hasPreviousPage=false,
 hasNextPage=true, navigatePages=1,
 navigateFirstPage1, navigateLastPage1, navigatepageNums=[1]}

要了解的:size-->每一页的真实数  ;prePage-->上一页的页码数  ;nextPage-->下一页的页码数  ;
isFirstPage-->是否是第一页  ; isLastPage-->是否是最后一页 ;
hasPreviousPage---> 是否有上一页 ;hasNextPage--->是否有下一页;
navigatePages--->导航分页数(下面的哪个);navigateFirstPage-->导航分页从第几行开始 ;
navigateLastPage--> 导航分页到第几行结束;navigatepageNums-->显示当前的导航数(集合显示)


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值