SSM整合

SSM整合

1.在数据库中创建表,并导入数据

sql语句

CREATE DATABASE wyy_music;

USE wyy_music;

DROP TABLE IF EXISTS `tb_music`;
CREATE TABLE `tb_music` (
  `music_id` INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, -- 歌曲ID
  `music_name` VARCHAR(255) NOT NULL, -- 歌曲名称
  `music_album_name` VARCHAR(255) NOT NULL, -- 专辑名称
  `music_album_picUrl` VARCHAR(255) NOT NULL, -- 专辑图片路径
  `music_mp3Url` VARCHAR(255) NOT NULL, -- 歌曲播放路径
  `music_artist_name` VARCHAR(255) NOT NULL, -- 歌手名称
  `sheet_id` INT(11) DEFAULT NULL -- 对应的歌单ID
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO tb_music VALUES ('1', '光年之外', '光年之外', 'https://imgessl.kugou.com/stdmusic/20161229/20161229233400375274.jpg', 'https://webfs.tx.kugou.com/202109061310/31fb3f36e2048b2172a70e327bbfc8e3/KGTX/CLTX001/f87095bff0de7c636c3a3b8aac702d76.mp3', 'G.E.M.邓紫棋','1');
INSERT INTO tb_music VALUES ('2', '夜空中最亮的星', '世界', 'https://imgessl.kugou.com/stdmusic/20150719/20150719010047203836.jpg', 'https://webfs.ali.kugou.com/202109061306/1b30ae27a5749debd602507b3bf1fea6/G202/M04/1B/13/aocBAF55G0-ADd0HAD2Y88Efqbw072.mp3', '逃跑计划','1');
INSERT INTO tb_music VALUES ('3', '只要平凡', '只要平凡', 'https://imgessl.kugou.com/stdmusic/20180622/20180622194005815458.jpg', 'https://webfs.ali.kugou.com/202109061309/edb2e89d90e66b9d125950dba107e9eb/KGTX/CLTX001/38aead7ed546b0736791ebb25c3a3951.mp3', '张杰/张碧晨','2');
INSERT INTO tb_music VALUES ('4', '光年之外', '光年之外', 'https://imgessl.kugou.com/stdmusic/20161229/20161229233400375274.jpg', 'https://webfs.tx.kugou.com/202109061310/31fb3f36e2048b2172a70e327bbfc8e3/KGTX/CLTX001/f87095bff0de7c636c3a3b8aac702d76.mp3', 'G.E.M.邓紫棋','1');
INSERT INTO tb_music VALUES ('5', '夜空中最亮的星', '世界', 'https://imgessl.kugou.com/stdmusic/20150719/20150719010047203836.jpg', 'https://webfs.ali.kugou.com/202109061306/1b30ae27a5749debd602507b3bf1fea6/G202/M04/1B/13/aocBAF55G0-ADd0HAD2Y88Efqbw072.mp3', '逃跑计划','1');
INSERT INTO tb_music VALUES ('6', '只要平凡', '只要平凡', 'https://imgessl.kugou.com/stdmusic/20180622/20180622194005815458.jpg', 'https://webfs.ali.kugou.com/202109061309/edb2e89d90e66b9d125950dba107e9eb/KGTX/CLTX001/38aead7ed546b0736791ebb25c3a3951.mp3', '张杰/张碧晨','2');


DROP TABLE IF EXISTS `tb_sheet`;
CREATE TABLE `tb_sheet` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sheet_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO tb_sheet VALUES ('1', '热歌榜');
INSERT INTO tb_sheet VALUES ('2', '新歌榜');
INSERT INTO tb_sheet VALUES ('3', '原创榜');

2.创建web工程,导入依赖

<dependencies>

    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.20</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.20</version>
    </dependency>

    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.9.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.20</version>
    </dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.9</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>

    <!-- servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>

    <!-- jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.3</version>
    </dependency>

    <!-- 分页 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.3.0</version>
    </dependency>

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

</dependencies>

3.配置相关properties文件

3.1关联数据库db.properties

db.username = root
db.password = root
db.url = jdbc:mysql:///wyy_music?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db.driverClassName = com.mysql.cj.jdbc.Driver

3.2日志log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.配置web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- 考虑:spring相关配置文件的加载时机
  spring配置文件的生命周期恰好和ServletContext对象的生命周期一致
  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 用于加载applicationContext.xml -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 前端控制器 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
    <!-- 加载springmvc.xml -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

5.编写 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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" 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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->


    <!-- 导入外部配置文件 db.properties -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!-- 配置数据源对象 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 导入 db.properties 中的值-->
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="driverClassName" value="${db.driver}"></property>
    </bean>

    <!-- 扫描对应包下的注解 -->
    <context:component-scan base-package="com.qf"></context:component-scan>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 必选配置 -->
        <property name="dataSource" ref="datasource"></property>
        <!-- 非必选属性,根据自己需求去配置 -->
        <!-- 导入 mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 导入 Mapper.xml 文件,classpath后面不能有空格 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

    </bean>

    <!-- 扫描 Mapper 接口,生成代理对象 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的具体位置 -->
        <property name="basePackage" value="com.qf.mapper"></property>
    </bean>

</beans>

6.编写 springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置springmvc中的组件
     我们用到的 映射器,适配器,解析器 这三个组件都已经帮我们创建好了
     -->
    <mvc:annotation-driven/>

    <!-- 扫描包下的注解,只对 Controller 进行扫描,否则会覆盖 applicationContext.xml 已经扫描的内容 -->
    <context:component-scan base-package="com.qf.controller"></context:component-scan>

    <!-- 放行静态资源 -->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

7.编写 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="logImpl" value="LOG4J"/>
    </settings>

</configuration>

8.编写实体类

Music

package com.qf.pojo;

import lombok.Data;

/**
 * CREATE TABLE `tb_music` (
 * `music_id` int(11) NOT NULL AUTO_INCREMENT, -- 歌曲ID
 * `music_name` VARCHAR(255) NOT NULL, -- 歌曲名称
 * `music_album_name` VARCHAR(255) NOT NULL, -- 专辑名称
 * `music_album_picUrl` VARCHAR(255) NOT NULL, -- 专辑图片路径
 * `music_mp3Url` VARCHAR(255) NOT NULL, -- 歌曲播放路径
 * `music_artist_name` VARCHAR(255) NOT NULL, -- 歌手名称
 * `sheet_id` int(11) DEFAULT NULL, -- 对应的歌单ID
 * PRIMARY KEY (`music_id`)
 * ) ENGINE=INNODB DEFAULT CHARSET=utf8;
 */

//歌曲
@Data
public class Music {

    private Integer musicId;
    private String musicName;
    private String musicAlbumName;
    private String musicAlbumPicurl;
    private String musicMp3url;
    private String musicArtistName;
    private Integer sheetId;

}

9.编写Mapper接口

MusicMapper

package com.qf.mapper;

import com.qf.pojo.Music;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MusicMapper {

    /**
     * 查询所有歌曲
     * @return
     */
    public List<Music> findAll();
    
}

10.编写Mapper.xml文件

MusicMapper.xml配置文件( 注意:存放位置和applicationContext.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.qf.mapper.MusicMapper">

    <resultMap id="musicMap" type="com.qf.pojo.Music">
        <id property="musicId" column="music_id"></id>
        <result property="musicName" column="music_name"></result>
        <result property="musicAlbumName" column="music_album_name"></result>
        <result property="musicAlbumPicurl" column="music_album_picUrl"></result>
        <result property="musicMp3url" column="music_mp3Url"></result>
        <result property="musicArtistName" column="music_artist_name"></result>
        <result property="sheetId" column="sheet_id"></result>
    </resultMap>
    
    <!-- sql判断 -->
    <sql id="baseSql">
        select music_id,
               music_name,
               music_album_name,
               music_album_picUrl,
               music_mp3Url,
               music_artist_name,
               sheet_id
        from tb_music
    </sql>

    <!-- 查询所有歌曲 -->
    <select id="findAll" resultMap="musicMap">
        <include refid="baseSql"></include>
    </select>
    
</mapper>

11.编写 Service

MusicService接口

package com.qf.service;

import com.qf.pojo.Music;

import java.util.List;

public interface MusicService {

    /**
     * 查询所有歌曲
     * @return
     */
    public List<Music> findAll();
}

12.编写ServiceImpl

MusicServiceImpl实现类

package com.qf.service.impl;

import com.qf.mapper.MusicMapper;
import com.qf.pojo.Music;
import com.qf.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service层,业务逻辑层
 */
@Service
public class MusicServiceImpl implements MusicService {

    @Autowired
    private MusicMapper musicMapper;

    /**
     * 实现查询所有歌曲
     * @return
     */
    @Override
    public List<Music> findAll() {
        return musicMapper.findAll();
    }
}

13.编写Controller

MusicController

package com.qf.controller;

import com.qf.pojo.Music;
import com.qf.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("music")
public class MusicController {
    
    @Autowired
    private MusicService musicService;

    /**
     * 查询所有歌曲
     * @return
     */
    @RequestMapping("findAll")
    public List<Music> findAll(){
        return musicService.findAll();
    }
}

14.测试

访问:localhost:8080/music/findAll 进行测试

15.多文件配置

首先设置之前的applicationContext.xml失效,在文件名后面加.bak -> applicationContext.xml.bak

15.1AOP配置

applicationContext-aop.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" 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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

    <!-- AOP配置(使用xml方式配置) -->
    <!-- 配置通知 -->
    <bean id="myAdvice" class="com.qf.advice.MyAdvice"></bean>

    <!-- 配置aop -->
    <aop:config>
        <!-- 配置切点
         expression:表达式,指定哪些方法是切入点,对那些进行增强
         -->
        <aop:pointcut id="pc" expression="execution(public * com.qf.service.impl.MusicServiceImpl.findAll())"/>

        <!-- 配置切面,把通知配置到切点上 -->
        <aop:aspect ref="myAdvice">
            <!-- aop:before 前置通知,method 表示增强的代码的方法名 -->
            <aop:before method="before" pointcut-ref="pc"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>

MyAdvice

package com.qf.advice;


/**
 * 通知类:增强的代码
 * 方法名以及功能可以是任意的
 */
public class MyAdvice {

    public void before(){
        System.out.println("前置通知,目标对象调用方法前执行");
    }

}

15.2事务配置

applicationContext-tx.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" 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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->


    <!-- 配置数据源对象 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 导入 db.properties 中的值-->
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="driverClassName" value="${db.driver}"></property>
    </bean>
    

    <!-- 配置事务(使用xml方式配置) -->
    <!-- 事务平台管理器,封装了所有的事务操作,依赖数据源 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 对那些方法配置事务
                isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
                propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
                read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
                timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
                rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
        -->
        <tx:attributes>
            <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置织入 -->
    <aop:config>
        <!-- 配置切点 -->
        <aop:pointcut id="txPc" expression="execution( * com.qf.service.impl.*ServiceImpl.*(..))"/>
        <!-- 配置切面 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"></aop:advisor>
    </aop:config>

</beans>

15.3常规配置

applicationContext-bean.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" 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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->


    <!-- 导入外部配置文件 db.properties -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!-- 配置数据源对象 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 导入 db.properties 中的值-->
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="driverClassName" value="${db.driver}"></property>
    </bean>

    <!-- 扫描对应包下的注解 -->
    <context:component-scan base-package="com.qf"></context:component-scan>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 必选配置 -->
        <property name="dataSource" ref="datasource"></property>
        <!-- 非必选属性,根据自己需求去配置 -->
        <!-- 导入 mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 导入 Mapper.xml 文件,classpath后面不能有空格 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

    </bean>

    <!-- 扫描 Mapper 接口,生成代理对象 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的具体位置 -->
        <property name="basePackage" value="com.qf.mapper"></property>
    </bean>

</beans>

15.4修改web.xml

<!-- 如果配置文件较多,可以采用通配符的方式去配置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>

16.添加分页操作

16.1.导入依赖(之前已经导入)

<!-- 分页 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.3.0</version>
</dependency>

16.2配置分页插件(两种方式)

16.2.1 第一种:在 applicationContext.xml 中添加配置
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 必选配置 -->
        <property name="dataSource" ref="datasource"></property>
        <!-- 非必选属性,根据自己需求去配置 -->
        <!-- 导入 mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 导入 Mapper.xml 文件,classpath后面不能有空格 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>

        <!-- 配置分页 -->
        <!--      <property name="plugins">
                  <array>
                      <bean class="com.github.pagehelper.PageInterceptor">
                          <property name="properties">
                              &lt;!&ndash;使用下面的方式配置参数,一行配置一个 &ndash;&gt;
                              <value>
                                  helperDialect = mysql
                                  reasonable = true
                                  supportMethodsArguments = true
                              </value>
                          </property>
                      </bean>
                  </array>
              </property>-->

    </bean>
16.2.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="logImpl" value="LOG4J"/>
    </settings>

    <!-- 分页插件 -->
    <plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 数据库方言,指定对应的数据库进行分页 -->
            <property name="helperDialect" value="mysql"/>
            <!-- 分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页 -->
            <property name="reasonable" value="true"/>
            <!-- 支持通过 Mapper 接口参数来传递分页参数 -->
            <property name="supportMethodsArguments" value="true"/>
        </plugin>
    </plugins>

</configuration>

16.3在 controller 中添加方法

    /**
     * 分页
     * @param pageNum
     * @param pageSize
     * @return
     */
//    @RequestMapping("findByPage")
//    public PageInfo findByPage(
//          @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
//          @RequestParam(value = "pageSize",required = false,defaultValue = "2")  Integer pageSize
//    ){
//        //设置分页数据
//        PageHelper.startPage(pageNum,pageSize);
//        //查询所有
//        List<Sheet> sheetList = sheetService.findAll();
//        //封装PageInfo
//        PageInfo<Sheet> sheetPageInfo = new PageInfo<>(sheetList);
//        //返回
//        return sheetPageInfo;
//    }

    
    /**
     * 分页,返回值类型不同,需要先创建JsonResult
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("findByPage")
    public JsonResult<Sheet> findByPage(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",required = false,defaultValue = "2")  Integer pageSize
    ){
        //设置分页数据
        PageHelper.startPage(pageNum,pageSize);
        //查询所有
        List<Sheet> sheetList = sheetService.findAll();
        //封装PageInfo
        PageInfo<Sheet> sheetPageInfo = new PageInfo<>(sheetList);
        //封装到JsonResult
        if(null != sheetList){
            JsonResult jsonResult = JsonResult.ok();
            //返回分页数据
            jsonResult.setData(sheetPageInfo.getList());

            return jsonResult;
        }
        //throw new RuntimeException("歌单查询有误");
        return JsonResult.fail();
    }

16.4创建JsonResult

package com.qf.utils;

import lombok.Data;

/**
 * 封装前端要求传递的数据格式
 */
@Data
public class JsonResult<T> {

    private Integer code;
    private String msg;
    private T data;

    /**
     * 成功返回
     * @return
     */
    public static JsonResult ok(){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(200);
        jsonResult.setMsg("success");

        return jsonResult;
    }

    /**
     * 失败返回
     * @return
     */
    public static JsonResult fail(){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(-2000);
        jsonResult.setMsg("error");

        return jsonResult;
    }
}
posted @ 2022-07-10 18:35  qtyanan  阅读(24)  评论(0编辑  收藏  举报