Mybatis学习记录

Mybatis基础搭建测试:

1、Mapper接口:

package com.zhaojianhui.mybatis.mapper;

import com.zhaojianhui.mybatis.pojo.User;

public interface UserMapper {
    User getUserById(String id);
}

2、Mapper.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.zhaojianhui.mybatis.mapper.UserMapper">
    <select id="getUserById" resultType="com.zhaojianhui.mybatis.pojo.User">
        select * from User where id = #{id}

    </select>

</mapper>

3、log4j.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>

</log4j:configuration>

4、mybatis-config.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="jdbc.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <!--创建别名,默认是类名不区分大小写-->
        <package name="com.zhaojianhui.mybatis.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
View Code

 

 

5、jdbc.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatisstudy?serverTimezone=UTC&characterEncoding=utf8&useSSL=false
db.username=root
db.password=1314520

6、测试代码:

package com.zhaojianhui.mybatis.test;

import com.zhaojianhui.mybatis.mapper.UserMapper;
import com.zhaojianhui.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

public class TestMybatis {
    public static void main(String[] args) throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById("2");
        System.out.println(user);
    }


}
View Code

 

7、实体类

package com.zhaojianhui.mybatis.pojo;

public class User {
    private Integer id;
    private String username;
    private String password;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
View Code

 

8、输出结果:

 

 TIPS:调用getMapper()方法时会通过动态代理生成代理类的实现类

 

Mybatis的基本crud:

1、测试代码

package com.zhaojianhui.mybatis.test;

import com.zhaojianhui.mybatis.mapper.EmpMapper;
import com.zhaojianhui.mybatis.mapper.UserMapper;
import com.zhaojianhui.mybatis.pojo.Emp;
import com.zhaojianhui.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

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

public class TestMybatis {
    public static void main(String[] args) throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //SqlSession sqlSession = sqlSessionFactory.openSession();//需要手动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//自动处理事务
      /*  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById("2");
        System.out.println(user);*/
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        //mapper.add(new Emp(null, "秦始皇", 28, "男"));
        //sqlSession.commit();
        //List<Emp> all = mapper.getAll();
        //System.out.println(all);
       /* Emp emp = mapper.getEmpById("2");
        System.out.println(emp);*/
        //mapper.updateById(new Emp(2,"李琪",28,"男"));
        mapper.deleteById("5");
        sqlSession.close();

    }


}
View Code

 

2、Mapper文件

<?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.zhaojianhui.mybatis.mapper.EmpMapper">
    <select id="getEmpById" resultType="Emp">
        select eid,ename,age,sex from emp where eid=#{eid}
    </select>
    <select id="getAll" resultType="Emp">
        select eid,ename,age,sex from emp;
    </select>
    <insert id="add">
        insert into emp values(null,#{ename},#{age},#{sex})
    </insert>
    <update id="updateById">
        update emp set ename=#{ename} ,age=#{age} ,sex=#{sex} where eid=#{eid}
    </update>
    <delete id="deleteById">
        delete from emp where eid=#{eid}
    </delete>

</mapper>
View Code

 

3、mybatis配置文件

<?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="jdbc.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <!--创建别名,默认是类名不区分大小写-->
        <package name="com.zhaojianhui.mybatis.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
        <mapper resource="EmpMapper.xml"/>
    </mappers>
</configuration>
View Code

 

4、Mapper接口

package com.zhaojianhui.mybatis.mapper;

import com.zhaojianhui.mybatis.pojo.Emp;

import java.util.List;

public interface EmpMapper {
    //根据Id查询员工信息
    Emp getEmpById(String eid);

    //获取所有员工信息
    List<Emp> getAll();

    //添加员工信息
    void add(Emp emp);


    //修改员工信息
    void updateById(Emp emp);

    //删除员工信息
    void deleteById(String eid);
}
View Code

 

Mybatis配置文件中注册多个mapper可以用<package/>注册,但是此时mapper接口所在包和mapper映射文件所在包得同名,如下图:

 

 

 

 

也可使用Map集合获取查询信息:

 //以map集合获取一个员工信息
    Map<String,Object> getMapById(String eid);
    //以map集合获取所有员工信息
    @MapKey("eid")//设置map的键
    Map<String,Object> getAllMap();

  

 <select id="getMapById" resultType="Map">
        select eid,ename,age,sex from emp where eid=#{eid}
    </select>
    <select id="getAllMap" resultType="Map">
         select eid,ename,age,sex from emp;
    </select>

 

Mybatis获取参数值的两种方式${}和#{}:

${}:必须使用字符串拼接方式操作SQL语句,类似原生jdbc的statement,不可以防止SQL注入,要注意单引号问题。

#{}:可以使用通配符操作SQL,类似原生jdbc的Preparedstatement,可以防止SQL注入

建议:尽量用#{}.特殊情况如模糊查询和批量删除时用${}

 

 

获取主键值:在insert中加入下面两个属性即可

 

 

 

 

Mybatis获取不同参数值的方式:

 多对一自定义映射(以员工和部门为例,一个部门对应多个员工):设置返回的结果集,id里面存放的是主键关系,SQL语句用左外连接或者右外连接。

 <resultMap id="empMap" type="Emp">
        <id column="eid" property="eid"/>
        <result column="ename" property="ename"/>
        <result column="age" property="age"/>
        <result column="sex" property="sex"></result>
        <result column="did" property="dept.did"/>
        <result column="dname" property="dept.dname"/>
    </resultMap>
    <select id="getAllEmps" resultMap="empMap">
        select e.eid,e.ename,e.age,e.sex,e.did,d.dname from emp e left join dept d on e.did=d.did
    </select>

 

使用association完成多对一映射:

 

 <resultMap id="empMap" type="Emp">
        <id column="eid" property="eid"/>
        <result column="ename" property="ename"/>
        <result column="age" property="age"/>
        <result column="sex" property="sex"></result>
        <association property="dept" javaType="Dept">
            <id column="did" property="did"/>
            <result column="dname" property="dname"/>
        </association>
    </resultMap>

 

多对一分步查询示例:

package com.zhaojianhui.mybatis.mapper;

import com.zhaojianhui.mybatis.pojo.Dept;

public interface DeptMapper {

    Dept getDeptById(String did);


}

  

package com.zhaojianhui.mybatis.mapper;

import com.zhaojianhui.mybatis.pojo.Emp;

import java.util.List;

public interface EmpDeptMapper {
    List<Emp> getAllEmps();

    Emp getEmpStep(String eid);
}

  

<?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.zhaojianhui.mybatis.mapper.DeptMapper">
    <select id="getDeptById" resultType="Dept">
        select did,dname from dept where did =#{did}
    </select>

</mapper>

  

 <resultMap id="empMapStep" type="Emp">
        <id column="eid" property="eid"/>
        <result column="ename" property="ename"/>
        <result column="age" property="age"/>
        <result column="sex" property="sex"></result>
        <association property="dept" select="com.zhaojianhui.mybatis.mapper.DeptMapper.getDeptById" column="did"></association>
    </resultMap>
    <select id="getEmpStep" resultMap="empMapStep">
        select eid,ename,age,sex,did from emp where eid=#{eid}
    </select>

 


分步查询的延迟加载:

 <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--是否查询所有数据-->
        <setting name="aggressiveLazyLoading" value="false"/>
        
    </settings>

 

分步查询的延迟加载控制fetch Type:

 

<association property="dept" select="com.zhaojianhui.mybatis.mapper.DeptMapper.getDeptById" column="did" fetchType="lazy"></association>

,设置为eager属性时为不延迟加载

 


 

 

动态SQL:

1、if示例:通过test表达式拼接SQL语句

 

 

 

 

2:where:添加where关键字同时去掉多余的and

 

 

 

 

 

 

 3:trim:截取并拼接

 

 

常用属性:

 

 

4:set:解决修改操作SQL语句中可能多出逗号问题

5:choose:choose里面只有一个条件会被执行,如果所有的when都不符合则执行otherwise

 <select id="getByChoose" resultType="Emp">
        select eid,ename,age,sex from emp
        where
        <choose>
            <when test="eid!=null">
                eid=#{eid}
            </when>
            <when test="ename!=null and ename!=''">
                ename=#{ename}
            </when>
            <when test="age!=null">
                age=#{age}
            </when>
            <otherwise>
                sex=#{sex}
            </otherwise>
        </choose>
    </select>

批量删除

方式一:

//通过eid组成的字符串实现批量删除
    void deleteMore(String eids);

  

 String eids = "6,7,8";
        mapper.deleteMore(eids);

  

  <delete id="deleteMore">
        delete from emp where eid in (${value})
    </delete>

  方式二:使用foreach实现批量删除

 

 //通过list集合实现批量删除
    void deleteByList(List<Integer> eids);

  

 <!--foreach用于对数组或集合遍历,collection指定要遍历的集合或数组,item别名,close设置循环体结束内容,Open设置循环体开始内容
    separator设置每一次循环之间的分隔符,index若遍历的是List代表下标,遍历Map则代表键

    -->
    <delete id="deleteByList">
        delete from emp where eid in
        (
        <foreach collection="list" item="eid" separator=",">
            #{eid}
        </foreach>)
    </delete>

  

  List<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(9);
        mapper.deleteByList(list);

  


批量操作:

 

 

 

批量添加:

//批量添加
    void insertByArray(@Param("emps")Emp[] emps);

  

   <insert id="insertByArray">
        insert into emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.ename},#{emp.age},#{emp.sex},1)

        </foreach>
    </insert>

  

  Emp emps1 = new Emp(null, "沙宣", 29, "女", new Dept(1, "开发部"));
        Emp emps2 = new Emp(null, "沙", 29, "女", new Dept(2, "开发部"));
        Emp emps3 = new Emp(null, "宣", 29, "女", new Dept(1, "开发部"));
        Emp[] emps = {emps1, emps2, emps3};
        mapper.insertByArray(emps);

  

 

sql标签:

 

 

 

需要的地方引入这个sql片段:

 

 


Mybatis缓存:

 1、简介

Mybatis有两级缓存,默认只有一级缓存(SqlSession级别的缓存,也称本地缓存开启),二级缓存需要手动开启,它是基于namespace级别的缓存.为了提高拓展性,Mybatis定义了缓存接口cache,我们可以通过实现cache接口来自定义二级缓存。

2、一级缓存的使用

一级缓存对于同一个SqlSession的一个sql语句,执行之后就会存储在缓存中,下次执行相同的sql直接从缓存中取。

3、一级缓存失效的几种情况:

1)不同的sqlsession对应不同的一级缓存

2)同一个sqlsession但是查询条件不同

3)同一sqlsession两次查询期间执行了任意一次增删改操作(会自动清空缓存)

4)手动清空了缓存(调用clearCache方法)

 

 

二级缓存(全局作用域缓存

1、实体类需要可序列化

2、在sqlsession关闭或者提交后才会生效

3、使用步骤:

  1、mybatis配置文件中开启二级缓存:<setting name="cacheEnabled" value="true"/>

  2、需要使用二级缓存的映射文件处使用cache配置缓存:<cache/>

  3、pojo实现Serializable接口

4、二级缓存相关属性:

 

 

 缓存的常用属性:

 

 

 


第三方缓存(以ehcache为例):

1、配置cache标签:<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

2、导入jar包:

       <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.6.11</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
View Code

 

3、编写ehcache.xml配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="F:\mybatisStudy\cache"/>
    <defaultCache
            maxElementsInMemory="1"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>
View Code

 

4、settings中添加约束:

 

 

 

4、cache中引入type:

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

 5、编写测试类

 


逆向工程:

1、mbg.xml配置文件

<?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>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/mybatisstudy?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;nullCatalogMeansCurrent=true"
                        userId="root" password="1314520">
        </jdbcConnection>
        <!--生成JAVABean类存放位置-->
        <javaModelGenerator targetPackage="com.zhaojianhui.mybatis.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成mapper映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.zhaojianhui.mybatis.mappers" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <!--mapper接口生成-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhaojianhui.mybatis.mappers"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表的实体类名-->
        <table tableName="emp" domainObjectName="Emp" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
            <!-- <generatedKey column="id" sqlStatement="MySql" identity="true"/>-->
        </table>

    </context>
</generatorConfiguration>
View Code

 

2、pom.xml中添加plugin和依赖:

<plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.5</version>
                        </dependency>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>8.0.11</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>mybatis generator</id>
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <!--允许移动生成的文件-->
                        <verbose>true</verbose>
                        <!--允许自动覆盖文件-->
                        <overwrite>true</overwrite>
                        <configurationFile>
                            src/main/resources/mbg.xml
                        </configurationFile>
                    </configuration>
                </plugin>

 

 <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

3、run>>edit configurations>>+>>maven

 

 

 

 

 

 4、command line中输入:mybatis-generator:generate -e

5、右上角选择运行:

 

 

 6、测试结果:

 EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        EmpExample example = new EmpExample();
        EmpExample.Criteria c1 = example.createCriteria();
        c1.andAgeBetween(12, 16);
        List<Emp> emps = mapper.selectByExample(example);
        for (Emp emp : emps) {
            System.out.println(emp);
        }

  


 

分页插件pageHelper:

1、导入依赖

 <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>3.1</version>
        </dependency>

2、在mybatis全局配置文件中加入:

 <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

3、测试

 EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        PageHelper.startPage(4, 1);
        List<Emp> all = mapper.getAll();
        PageInfo<Emp> pageInfo = new PageInfo<>(all, 5);
        System.out.println(Arrays.toString(pageInfo.getNavigatepageNums()));
        System.out.println();
        for (Emp emp : all) {
            System.out.println(emp);
        }

  

 

模拟分页:

1、分页工具类:

package com.zhaojianhui.mybatis.util;

import com.github.pagehelper.PageInfo;
import com.zhaojianhui.mybatis.pojo.Emp;

import javax.servlet.http.HttpServletRequest;

public class PageUtil {
    public static String getPageInfo(PageInfo<Emp> pageInfo, HttpServletRequest request) {
        String path = request.getContextPath() + "/";
        StringBuilder builder = new StringBuilder();
        //拼接首页
        builder.append("<a href='" + path + "emps/1'>首页</a>");
        builder.append("&nbsp;&nbsp");
        //拼接上一页
        if (pageInfo.isHasPreviousPage()) {
            builder.append("<a href='" + path + "emps/" + pageInfo.getPrePage() + "'>上一页</a>");
            builder.append("&nbsp;&nbsp");
        } else {
            builder.append("上一页");
            builder.append("&nbsp;&nbsp");
        }
        //拼接下一页
        if (pageInfo.isHasPreviousPage()) {
            builder.append("<a href='" + path + "emps/" + pageInfo.getNextPage() + "'>下一页</a>");
            builder.append("&nbsp;&nbsp");
        } else {
            builder.append("下一页");
            builder.append("&nbsp;&nbsp");
        }
        //拼接页码
        int[] nums = pageInfo.getNavigatepageNums();
        for (int i : nums) {
            if (i == pageInfo.getPageNum()) {
                builder.append("<a style='color:red;' href='" + path + "emps/" + i + "'>" + i + "</a>");
                builder.append("&nbsp;&nbsp");
            } else {
                builder.append("<a href='" + path + "emps/" + i + "'>" + i + "</a>");
                builder.append("&nbsp;&nbsp");
            }

        }
        //拼接尾页
        builder.append("<a href='" + path + "emps/" + pageInfo.getPages() + "'>尾页</a>");
        builder.append("&nbsp;&nbsp");
        return builder.toString();
    }
}
View Code

 

 

SSM整合步骤:

1、导入jar

  Spring、SpringMVC、mybatis、第三方支持:如log4j、pageHelper、AspectJ、jackson、jstl

2、搭建springmvc

  1、web.xml:DispatcherServlet、HiddenHttpMethodFilter、CharacterEncodingFilter

  2、spring-servlet.xml:扫描控制层组件、视图解析器、Default Servlet、MVC驱动、可选:MultipartResolver,拦截器

3、整合SpringMVC和Spring

  1、web.xml:ContextLoaderListener、context-param

  2、applicationContext.xml:扫描组件(排除控制层)、事务管理器

4、搭建Mybatis:核心配置文件、mapper接口和映射文件

5、spring整合Mybatis

  applicationContext.xml:properties文件的引入、Datasource数据源的配置、事务管理器、开启事务驱动、SqlSessionFactoryBean:管理SqlSession、MapperScannerConfigurer

6、测试CRUD

 

配置文件:

1)applicationContext.xml:

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:component-scan base-package="com.zhaojianhui">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--引入资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${db.driver}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>

    </bean>
    <!--声明事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解驱动-->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
    <!--管理mybatis会话对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--设置mybatis文件路径-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--设置别名——-->
        <property name="typeAliasesPackage" value="com.zhaojianhui.pojo"/>
        <!--设置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--设置映射文件路径-->
        <property name="mapperLocations" value="classpath:com/zhaojianhui/mapper/*Mapper.xml"/>
    </bean>
    <!--Mapper接口生成代理实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zhaojianhui.mapper"></property>
    </bean>
</beans>
View Code

 

2)mybatis-config.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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--  <!–开启延迟加载–>
          <setting name="lazyLoadingEnabled" value="true"/>
          <!–是否查询所有数据–>
          <setting name="aggressiveLazyLoading" value="false"/>-->
        <!--是否开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>

    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

</configuration>

3)springMVC-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描组件,将加上@Controller的类作为控制层-->
    <context:component-scan base-package="com.zhaojianhui.controller"></context:component-scan>
    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--处理静态资源-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <!--配置文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>


    <!--异常处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">error</prop>
            </props>
        </property>
    </bean>


</beans>

4)web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!--配置核心控制器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>

    </filter-mapping>
    <!--默认web-info下applicationContext.xml-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>
View Code

 

5)pom.xml

   <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
View Code

 6)jdbc.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatisstudy?serverTimezone=UTC&characterEncoding=utf8&useSSL=false
db.username=root
db.password=1314520

7)log4j.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>

</log4j:configuration>

8)mbg.xml:

<?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>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/mybatisstudy?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;nullCatalogMeansCurrent=true"
                        userId="root" password="1314520">
        </jdbcConnection>
        <!--生成JAVABean类存放位置-->
        <javaModelGenerator targetPackage="com.zhaojianhui.mybatis.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成mapper映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.zhaojianhui.mybatis.mappers" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->
        <!--mapper接口生成-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zhaojianhui.mybatis.mappers"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表的实体类名-->
        <table tableName="emp" domainObjectName="Emp" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="true" selectByExampleQueryId="false">
            <!-- <generatedKey column="id" sqlStatement="MySql" identity="true"/>-->
        </table>

    </context>
</generatorConfiguration>
View Code

 

posted @ 2020-08-17 15:58  zhaojianhui  阅读(193)  评论(0编辑  收藏  举报