Mybatis+SSM整合

简介

官方文档:链接

MyBatis作用

  1. MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
  2. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
  3. MyBatis可以使用简单的XML用于配置和原始映射,将接口和Java的POJO类映射成数据库中的记录
  4. 使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。

历史

  1. 原是apache的一个开源项目iBatis
  2. 2010年6月这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
  3. iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。

为什么要使用MyBatis?

JDBC

  1. SQL夹在Java代码块里,耦合度高导致硬编码内伤
  2. 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见
  3. 要自已创建connection、创建statement、手动设置参数、结果集检索等

Hibernate

  1. 长难复杂SQL,对于Hibernate而言处理也不容易
  2. 内部自动生产的SQL,不容易做特殊优化。
  3. 基于全映射的全自动框架,javaBean存在大量字段时无法只映射部分字段。导致数据库性能下降。

Mybatis

  1. 对开发人员而言,核心sql还是需要自己优化
  2. MyBatis是一个半自动化的持久化层框架。
  3. MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。

MyBatis入门程序

1. 创建 jar工程

2. 导入jar包

在这里插入图片描述

3. 创建数据库

在这里插入图片描述

/*
Navicat MySQL Data Transfer

Source Server         : itlike
Source Server Version : 50720
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50720
File Encoding         : 65001

Date: 2018-12-04 14:13:49
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for customer
-- ----------------------------
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `cust_id` int(11) NOT NULL AUTO_INCREMENT,
  `cust_name` varchar(255) DEFAULT NULL,
  `cust_profession` varchar(255) DEFAULT NULL,
  `cust_phone` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES ('1', '鲁班', '射手', '13499887733', '12341241@qq.com');
INSERT INTO `customer` VALUES ('2', '李白', '刺客', '18977665521', 'libai@163.com');
INSERT INTO `customer` VALUES ('3', '阿轲', '刺客', '18977665997', 'aike@qq.com');
INSERT INTO `customer` VALUES ('4', '德玛西亚', '肉盾', '13700997665', 'demaxiya.126.com6');
INSERT INTO `customer` VALUES ('5', '亚索', '战士', '13586878987', 'yasuo@qq.com');
INSERT INTO `customer` VALUES ('6', '奶妈', '辅助', '13398909089', 'nama@qq.com');
INSERT INTO `customer` VALUES ('7', '剑圣', '刺客', '13398909088', 'jiansheng@163.com');
INSERT INTO `customer` VALUES ('8', '盖伦', '肉盾', '15923242231', 'gailun@126.com');
INSERT INTO `customer` VALUES ('9', '锤石', '辅助', '13398908900', '8888@163.com');
INSERT INTO `customer` VALUES ('10', '阿木木', '辅助', '13398908928', '13398908928@qq.com');

4. 建立关系映射类pojo

在这里插入图片描述

@Getter@Setter//Lombok插件
public class Customer {
    private Integer cust_id;
    private String cust_name;
    private String cust_profession;
    private String cust_phone;
    private String email;

    @Override
    public String toString() {
        return "Customer{" +
                "cust_id=" + cust_id +
                ", cust_name='" + cust_name + '\'' +
                ", cust_profession='" + cust_profession + '\'' +
                ", cust_phone='" + cust_phone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

5. 创建核心配置文件SqlMappingConfig.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>
    <!-- spring整合后 environments配置将废除 使用spring中的连接池 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
</configuration>

6.创建与表对象的关系映射Mapping文件编写sql语句

Customer.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="myTest">
    <!--根据cust_id查询客户-->
    <select id="queryCustomerById" parameterType="Int" resultType="com.dj.domain.Customer">
        SELECT * FROM `customer` WHERE cust_id  = #{cust_id}
    </select>
</mapper>

7. 在核心配置文件当中引入Mapping

在这里插入图片描述

 <!--加载映射文件-->
    <mappers>
        <mapper resource="com\dj\domain\Customer.xml"></mapper>
    </mappers>

8.创建工厂,执行sql语句

在这里插入图片描述

public class Test01 {
    @Test
    public void test() throws IOException {
        //1.SqlSessionFactoryBuilder 加载配置文件
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.读取配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMappingConfig.xml");
        //3.获取session工厂
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        //4.创建会话 --JDBC链接
        SqlSession sqlSession = build.openSession();
        //5.执行sql语句
        Customer queryCustomerById = sqlSession.selectOne("queryCustomerById", 1);
        //6.打印信息
        System.out.println(queryCustomerById);
        //7.关闭会话
        sqlSession.close();
    }
}

在这里插入图片描述
执行流程:
在这里插入图片描述

MyBatis核心Api

SqlSessionFactoryBuilder

  1. SqlSessionFactoryBuilder用于创建SqlSessionFacoty
  2. SqlSessionFacoty一旦创建完成就不需要SqlSessionFactoryBuilder了
  3. 因为SqlSession是通过SqlSessionFactory创建的
  4. 所以可以将SqlSessionFactoryBuilder当成一个工具类使用,最佳使用范围是方法范围即方法体内局部变量。

SqlSessionFactory

  1. 创建sqlSession的工厂,是一个接口
  2. 接口中定义了openSession的不同重载方法
  3. SqlSessionFactory的最佳使用范围是整个应用运行期间,一旦创建后可以重复使用,通常以单例模式管理SqlSessionFactory。

SqlSession

  1. 连接到数据库的一个会话
  2. sqlSession中定义了数据库操作方法。
  3. 每个线程都应该有它自己的SqlSession实例
  4. SqlSession的实例不能共享使用,它也是线程不安全的。因此最佳的范围是请求或方法范围
  5. 绝对不能将SqlSession实例的引用放在一个类的静态字段或实例字段中。

MyBatis架构

在这里插入图片描述

mybatis封装工具类查询所有用户

在这里插入图片描述

public class mybatisutils {
    public static final SqlSessionFactory build;
    static {
        //1.SqlSessionFactoryBuilder 加载配置文件
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.读取配置文件
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("SqlMappingConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.获取session工厂
        build = sqlSessionFactoryBuilder.build(resourceAsStream);
    }

    public static SqlSession openSession(){
        return build.openSession();
    }
}

在这里插入图片描述

MyBatis-查询

查询所有用户

  1. 编写sql语句
    在这里插入图片描述
  2. 编写代码调用
    在这里插入图片描述
//查询所有的用户
    @Test
    public void test02(){
        SqlSession sqlSession = mybatisutils.openSession();
        List<Customer> queryCustomerAll = sqlSession.selectList("queryCustomerAll");
        System.out.println(queryCustomerAll);
        //7.关闭会话
        sqlSession.close();
    }

配置sql打印

在SqlMappingConfig.xml配置
在这里插入图片描述
执行sql语句
在这里插入图片描述

模糊查询Like

在这里插入图片描述
在这里插入图片描述

参数介绍

  1. parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中
  2. resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。如果有多条数据,则分别进行映射,并把对象放到容器List中
  3. selectOne:查询一条记录,如果使用selectOne查询多条记录则抛出异常
  4. selectList:可以查询一条或多条记录

#{}和${}

1. #{}:
  1. 表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值
  2. 自动进行java类型和jdbc类型转换
  3. #{}可以有效防止sql注入
  4. #{}可以接收简单类型值或pojo属性值
  5. 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称
2. ${}
  1. 表示拼接sql串
  2. 通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换
  3. $ {}可以接收简单类型值或pojo属性值
  4. 如果parameterType传输单个简单类型值,${}括号中只能是value
    在这里插入图片描述

保存更新删除

添加客户

在这里插入图片描述

  <!--添加客户-->
    <insert id="insertCustomer" parameterType="com.dj.domain.Customer">
        insert into customer(cust_name,cust_profession,cust_phone,email)values(#{cust_name},#{cust_profession},#{cust_phone},#{email})
    </insert>

在这里插入图片描述

 //添加用户
    @Test
    public void test04(){
        SqlSession sqlSession = mybatisutils.openSession();
        Customer customer = new Customer();
        customer.setCust_name("张飞");
        customer.setCust_phone("1684612684");
        customer.setCust_profession("肉盾");
        customer.setEmail("12515165@qq.com");
        //执行sql
        sqlSession.insert("insertCustomer", customer);
        //6.提交事务
        sqlSession.commit();
        //7.关闭会话
        sqlSession.close();
    }

在这里插入图片描述

返回添加过后自增的主键

在这里插入图片描述

 <!--添加客户-->
    <insert id="insertCustomer" parameterType="com.dj.domain.Customer">
        <!--获取插入的ID-->
        <selectKey keyColumn="cust_id" keyProperty="cust_id" order="AFTER" resultType="Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into customer(cust_name,cust_profession,cust_phone,email)values(#{cust_name},#{cust_profession},#{cust_phone},#{email})
    </insert>

在这里插入图片描述

更新操作

在这里插入图片描述
在这里插入图片描述

删除操作

在这里插入图片描述
在这里插入图片描述

MyBatis开发DAO

原始Dao开发方法

  1. 创建接口
    在这里插入图片描述
  2. 实现接口
    在这里插入图片描述
  3. 调用接口
    在这里插入图片描述

Mapper动态代理

要求

  1. namespace必须和Mapper接口类路径一致
  2. id必须和Mapper接口方法名一致
  3. parameterType必须和接口方法参数类型一致
  4. resultType必须和接口方法返回值类型一致
  1. 配置namespace
    在这里插入图片描述
  2. 创建mapper接口 方法名和xml一致
    在这里插入图片描述
  3. 调用
    在这里插入图片描述
selectOne和selectList
  1. 动态代理对象调用sqlSession.selectOne()和sqlSession.selectList()是根据mapper接口方法的返回值决定
  2. 如果返回list则调用selectList方法,如果返回单个对象则调用selectOne方法。

参数传递

单个参数

  1. 可以接受基本类型,对象类型,集合类型的值。
  2. MyBatis可直接使用这个参数,不需要经过任何处理。

多个参数

  1. 任意多个参数,都会被MyBatis重新包装成一个Map传入。
  2. Map的key是param1,param2…,值就是参数的值。
    在这里插入图片描述

在这里插入图片描述

@param命名参数

当这些参数属于我们业务POJO时,我们直接传递POJO
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Map

我们也可以封装多个参数为map,直接传递

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

MaBatis核心配置文件

properties

定义属性及读取属性文件

在这里插入图片描述

settings

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

在这里插入图片描述
在这里插入图片描述

typeAliases

类型别名是为 Java 类型设置一个短的名字

  1. 定义单个别名
    在这里插入图片描述
  2. 批量别名定义
    在这里插入图片描述
    如果当前包类与子包类重名,会有异常
    可以在类上使用注解@Alias(“别名”)

typeHandlers

  1. 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。
  2. JDK1.8之后实现全部的JSR310规范,日期时间处理上,我们可以使用MyBatis基于JSR310(Date and Time API)
  3. 编写的各种日期时间类型处理器。MyBatis3.4以前的版本需要我们手动注册这些处理器,以后的版本都是自动注册的

Plugins

  1. 插件是MyBatis提供的一个非常强大的机制,
  2. MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。
  3. 通过插件来修改MyBatis的一些核心行为。

Environments

  1. MyBatis可以配置多种环境,比如开发、测试和生产环境需要有不同的配置。
  2. 每种环境使用一个environment标签进行配置并指定唯一标识符
  3. 可以通过environments标签中的default属性指定一个环境的标识符来快速的切换环境

Environment子标签

  1. transactionManager事务管理
    Type有以下取值:
    JDBC:使用JDBC 的提交和回滚设置,依赖于从数据源得到的连接来管理事务范围
    MANAGED:不提交或回滚一个连接、让容器来管理事务的整个生命周期ManagedTransactionFactory
    自定义:实现TransactionFactory接口 ,type=全类名/别名

  2. dataSource数据源
    type有以下取值:
    UNPOOLED:不使用连接池UnpooledDataSourceFactory
    POOLED:使用连接池PooledDataSourceFactory
    JNDI:在EJB 或应用服务器这类容器中查找指定的数据源
    自定义:实现DataSourceFactory接口,定义数据源的获取方式

  3. 实际开发
    实际开发中我们使用Spring管理数据源
    并进行事务控制的配置来覆盖上述配置

databaseIDProvider

MyBatis 可以根据不同的数据库厂商执行不同的语句。
可以能过databaseIDProvider标签来进行设置

<databaseIdProvider type="DB_VENDOR">
        <property name="MYSQL" value="mysql"/>
        <property name="DB2" value="db2"/>
        <property name="Oracle" value="oracle" />
        <property name="SQL Server" value="sqlserver"/>
    </databaseIdProvider>

在这里插入图片描述
在这里插入图片描述

mappers

  1. < mapper resource=" " >:使用相对于类路径的资源
    在这里插入图片描述
  2. < mapper class=" " />: 使用mapper接口类路径,此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中
    在这里插入图片描述
    在这里插入图片描述
  3. < package name=""/>: 指定包下的所有mapper接口,此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中
    在这里插入图片描述

输出类型

输出简单类型

在这里插入图片描述

Map

第1种形式:
key:是列名 value:是列名对应的值
在这里插入图片描述
第2种形式:
Map<key,自定义对象>:key为自己指定的我列
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

resultMap

  1. 之有在写输出时使用的都是resultType
  2. 但是resultType要求必须得要字段名称和数据库当中的名称一致时才能有值,否则为null
  3. 如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系

表名与domain
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

多表操作

ManyToOne

关系表
在这里插入图片描述
查询
分步查询
第一步 先查出所有的订单
在这里插入图片描述
第二步 根据id查出对应客户
在这里插入图片描述
左连接查询
查询所有的订单及订单所对应的客户
左连接:把左边表的数据全部查出,右边表只查出满足条件的记录

应对sql

SELECT * FROM `order` as o LEFT JOIN customer as c on o.cus_id = c.cust_id;

建立domain
在这里插入图片描述
建立Mapping映射
在这里插入图片描述
在这里插入图片描述
测试
在这里插入图片描述
分部查询懒加载

 <!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!--指定哪个对象的方法触发一次延迟加载。-->
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode"/>

OnToMany

查询
查询客户和客户订单
在这里插入图片描述
sql语句

SELECT * FROM customer as c LEFT JOIN `order` as o  on c.cust_id = o.cust_id;

映射
在这里插入图片描述
测试
在这里插入图片描述
添加
保存数据
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
维护外键
在这里插入图片描述
在这里插入图片描述
管理关系
在这里插入图片描述
删除
删除时一定要先打破关系再做删除操作
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

ManyToMany

关系表
在这里插入图片描述
查询
分步查询
查询出指定的老师
在这里插入图片描述
在这里插入图片描述

根据老师id查询出所有学生
在这里插入图片描述
在这里插入图片描述

查询
在这里插入图片描述
左边接查询
在这里插入图片描述
在这里插入图片描述

动态sql

什么是动态sql

通过mybatis提供的各种标签方法实现动态拼接sql。

. if标签

需求:根据客户名和级别查询客户
在这里插入图片描述
存在问题
有可能传入的名称或级别为空
可以使用if标签来进行判断
在这里插入图片描述

如果前一个条件这后,后面就会多一个and执行就会报错

Where标签

在这里插入图片描述
去掉第一个前And

trim标签

choose标签

foreach标签

查询条件值为指定的值当中在这里插入图片描述
给定的值可以以三种形式给出
数组:
在这里插入图片描述
List:
在这里插入图片描述
在这里插入图片描述
VO:
创建Vo
在这里插入图片描述
在这里插入图片描述

测试
在这里插入图片描述

bind标签

Sql片段

Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的。
在这里插入图片描述

缓存

一级缓存

缓存介绍

  1. MyBatis中使用缓存来提高其性能。
  2. 当查询数据时, 会先从缓存中取出数据,如果缓存中没有,再到数据库当中查询
  3. MyBatis中的缓存分为两种:一级缓存和二级缓存
  4. 一级缓存是sqlSession级别的,二级缓存是mapper级别的

一级缓存

  1. 本地缓存 (默认开启)
  2. 在sqlSession没有关闭之前,再去查询时, 会从缓存当中取出数据,不会重新发送新的sql

一级缓存失效

  1. 如果在查询之前,执行了增\删\改 缓存就会失效
  2. 手动清空缓存
  3. 如果两次的查询条件不一样,缓存也会失效
  4. 如果两个查询在不同的sqlsession当中

二级缓存

二级缓存介绍

  1. 全局作用域缓存 一个namespace对应一个缓存
  2. 如果会话关闭,一级缓存的数据会被保存到二级缓存中
  3. 不同namespace查出的数据 ,会放到自己对应的缓存中
  4. 现在默认也是打开的

二级缓存使用步骤

  1. 确保在配置文件当中开启二级缓存
    在这里插入图片描述

  2. 在对应的mapper中添加cache标签
    在这里插入图片描述
    在这里插入图片描述

    1. eviction:回收策略
      1. LRU(默认):最近最少使用,移除最长时间使用的对象
      2. FIFO:先进先出,俺对象进入缓存的顺序移除对象
      3. SOFT:软引入,移除基本垃圾回收器状态和软引入规则的对象
      4. WEAK:弱引入,移除基本垃圾回收状态和弱引入规则的对象
    2. flushInterval:刷新间隔,默认不清空
    3. readOnly:是否只读,
      1. true:告诉Mybatis是只读操作,不去修改数据,Mybatis为了加快获取速度,会直接将缓存的引用将给用, 不安全, 速度快
      2. false:非只读,有可能修改数据,Mybatis会利用序列化和反序列化复制一份给你 速度慢些
    4. size:可以存放多少个元素
    5. type:可以用来指定自定义的缓存
  3. POJO需要实现Serializable接口
    在这里插入图片描述

注意事项:

  1. 查询的数据都会先放到一级缓存当中
  2. 只有会话关闭,一级缓存中的数据才会转称到二级缓存中

缓存相关属性:

  1. cacheEnabled:只能控制二级缓存的开关
  2. select中useCache:控制的也是二级缓存是否使用
  3. 增删改标签中flushCache 一级和二级都会被清空 增删改flushCache默认为true 查询flushCache默认为false
  4. sqlSession.clearCache() 只清楚当前session的一级缓存
  5. localCacheScope:本地缓存作用域 取值:SESSION、STATEMENT、STATEMENT可以使用它禁用缓存

缓存使用顺序

  1. 先到二级缓存当中查找
  2. 如果二级缓存中没有,就去找一级缓存
  3. 如果一级缓存中也没有就去到数据库当中查询

逆向工程

MyBatis Generator

  1. 代码生成器
  2. 可以根据指定的表快速生成对应的映射文件,接口,以及Bean类
  3. 支持基本的增删改查,以及QBC风格的条件查询
  4. 但是一些复杂的表连接还是需要我们自己来去编写

使用

  1. 下载 https://github.com/mybatis/generator/releases
  2. 把相关jar导入到工程当中
  3. 创建generatorConfig.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>
    <!--
    targetRuntime:设置自动生成的版本
    MyBatis3:
    MyBatis3Simple:简单增删改查
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--
           不要生成日期和备注
        -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"
                        userId="root"
                        password="1234">
        </jdbcConnection>
        <!--
        配置domain生成策略
        targetProject:把自动生成的domian放在哪个工程里面
        targetPackage:哪个包下
        -->
        <javaModelGenerator targetPackage="com.itlike.domain" targetProject=".\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--
            配置mapper的生成策略
            targetPackage:把自动生成的mapper放在哪个工程里面
            targetProject:哪个包下
        -->
        <sqlMapGenerator targetPackage="com.itlike.mapper"  targetProject=".\src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!--
            mapper接口生成策略
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.itlike.mapper"  targetProject=".\src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <table tableName="customer" domainObjectName="Customer" ></table>
        <table tableName="teacher" domainObjectName="Teacher" ></table>
        <table tableName="student" domainObjectName="Student" ></table>
    </context>
</generatorConfiguration>
  1. 编写生成代码
 List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("./src/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

分页插件

  1. 下载分页插件
    下载地址

  2. 配置分页插件

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
  1. 使用分页插件
    在查询之前设置分页
 Page<Object> page = PageHelper.startPage(1, 5);

查询数据之后添加

PageInfo<Customer> pageInfo = new PageInfo<>(customers, 5);

属性介绍

        System.out.println("当前页:"+pageInfo.getPageNum());
        System.out.println("每页显示记录数:"+pageInfo.getPageSize());
        System.out.println("总页数:"+pageInfo.getPages());
        System.out.println("总记录数:"+pageInfo.getTotal());
        System.out.println("是否有上一页:"+pageInfo.isHasPreviousPage());
        System.out.println("是否有下一页:"+pageInfo.isHasNextPage());
        System.out.println("导航页面:"+ Arrays.toString(pageInfo.getNavigatepageNums()));

SSM整合

spring与springMVC

  1. 创建web动态工程
  2. 导入spring包与配置文件

相关jar包
在这里插入图片描述

   <dependencies>
      <!--Junit-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
      </dependency>

      <!--数据库驱动-->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
      </dependency>
      <!-- 数据库连接池 -->
      <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
      </dependency>

      <!--Servlet - JSP -->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>

      <!--Mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
      </dependency>
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
      </dependency>
      <!-- druid -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.14</version>
      </dependency>
      <!--Spring-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.73</version>
      </dependency>
    </dependencies>

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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--注解扫描-->
    <context:component-scan base-package="com.dj"/>
    <!--导入mybatis-->
    <import resource="classpath:application-mybatis.xml"/>

    <!--导入springMVC-->
    <import resource="classpath:application-mvc.xml"/>


</beans>
  1. 在web.xml当中配置spring监听器
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"
         metadata-complete="false">
  <absolute-ordering/>
  <display-name>web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--加载的主配置文件-->
      <param-value>classpath*:applicationContext.xml</param-value>
    </init-param>
    <!-- 项目启动就加载框架 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncoding</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-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
  1. 添加springMVC相关jar包
    在这里插入图片描述
  2. 添加springMVC配置文件
    application-mvc.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-4.0.xsd
	">

    <mvc:annotation-driven />
    <!--静态资源处理 -->
    <mvc:default-servlet-handler/>
    <!--扫描controller-->
    <context:component-scan base-package="com.dj.controller" />
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

添加Mybatis

添加Mybatis配置文件和数据库属性文件
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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
        <package name="com.myxq.domain" />
    </typeAliases>
</configuration>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

创建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.dj.mapper">
</mapper>
  1. 在applicationContext配置文件中添加Mybatis数据库相关配置信息
    application-mybatis.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">

    <!--spring-Mybatis整合-->
    <!--加载数据库属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--属性文件当中的名称不能和name名称一样-->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- Mybatis的工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
        <!--配置mapper映射文件的路径-->
        <property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
    </bean>

    <!-- 配置Mapper接口扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置Mapper扫描包 -->
        <property name="basePackage" value="com.dj.mapper" />
    </bean>

</beans>

SSM配置文件总结

pom.xml

  <dependencies>
      <!--Junit-->
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
      </dependency>

      <!--数据库驱动-->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
      </dependency>
      <!-- 数据库连接池 -->
      <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
      </dependency>

      <!--Servlet - JSP -->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
      </dependency>

      <!--Mybatis-->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.1</version>
      </dependency>
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
      </dependency>
      <!-- druid -->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.14</version>
      </dependency>
      <!--Spring-->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.0.RELEASE</version>
      </dependency>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
      </dependency>
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.73</version>
      </dependency>
    </dependencies>

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"
         metadata-complete="false">
  <absolute-ordering/>
  <display-name>web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--加载的主配置文件-->
      <param-value>classpath*:applicationContext.xml</param-value>
    </init-param>
    <!-- 项目启动就加载框架 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncoding</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-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

application-mvc.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-4.0.xsd
	">

    <mvc:annotation-driven />
    <!--静态资源处理 -->
    <mvc:default-servlet-handler/>
    <!--扫描controller-->
    <context:component-scan base-package="com.dj.controller" />
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/JSP/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

application-mybatis.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">

    <!--spring-Mybatis整合-->
    <!--加载数据库属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--属性文件当中的名称不能和name名称一样-->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- Mybatis的工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
        <!--配置mapper映射文件的路径-->
        <property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
    </bean>

    <!-- 配置Mapper接口扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置Mapper扫描包 -->
        <property name="basePackage" value="com.dj.mapper" />
    </bean>

</beans>

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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--注解扫描-->
    <context:component-scan base-package="com.dj"/>
    <!--导入mybatis-->
    <import resource="classpath:application-mybatis.xml"/>

    <!--导入springMVC-->
    <import resource="classpath:application-mvc.xml"/>


</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <typeAliases>
        <!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
        <package name="com.dj.entity" />
    </typeAliases>
 <!--   <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper"></plugin>
    </plugins>-->
</configuration>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值