欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2、springboot整合mybatis

程序员文章站 2024-01-26 15:34:28
...

目录:

1、springboot配置数据库连接池druid
2、springboot整合mybatis
3、springboot整合pagehelper

springboot配置数据库连接池druid

新建springboot项目

2、springboot整合mybatis

相关pom依赖

druid所需pom依赖

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.10</version>
  </dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>

配置application.yml


server:
  port: 80
  servlet:
    context-path: /

spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/t226_layui?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    username: root
    password: 123
    druid:
      #2.连接池配置
      #初始化连接池的连接数量 大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置获取连接等待超时的时间
      max-wait: 60000
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.基础监控配置
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #设置不统计哪些URL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        #设置监控页面的登录名和密码
        login-username: admin
        login-password: admin
        allow: 127.0.0.1
        #deny: 192.168.1.100


#pagehelper分页插件配置
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

#显示日志
logging:
  level:
    com.liuxia.springboot02.mapper: debug

HelloController

package com.liuxia.springboot02.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */
@RestController
@RequestMapping("/demo")
public class HelloController {

    @RequestMapping("/say1")
    public String say1(){
        return "说活1";
    }

    @RequestMapping("/say2")
    public String say2(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "说活2";
    }

    @RequestMapping("/say3")
    public String say3(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "说活3";
    }

}


springboot整合mybatis

springboot整合mybatis逆向生成插件

相关pom依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
    <scope>runtime</scope>
</dependency>

<resources>
    <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>*.properties</include>
            <include>*.xml</include>
            <include>*.yml</include>
        </includes>
    </resource>
</resources>

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <dependencies>
        <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>



Springboot02Applicatio

package com.liuxia.springboot02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("com.liuxia.springboot02.mapper")
@EnableTransactionManagement
@EnableAspectJAutoProxy
@SpringBootApplication
public class Springboot02Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02Application.class, args);
    }

}


BookServiceImplTest

package com.liuxia.springboot02.service.impl;
import com.liuxia.springboot02.entity.Book;
import com.liuxia.springboot02.service.BookService;
import com.liuxia.springboot02.utils.PageBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class BookServiceImplTest {
    @Autowired
    private BookService bookService;

    @Test
    public void deleteByPrimaryKey() {
     bookService.deleteByPrimaryKey(21);
    }

    @Test
    public void selectByPrimaryKey() {
        System.out.println(bookService.selectByPrimaryKey(16));
    }

    @Test
    public void listPage() {
        Book book = new Book();
        book.setBname("%十里桃花%");
        PageBean pageBean = new PageBean();
        pageBean.setPage(2);
        for (Book book1 : bookService.listPage(book,pageBean)) {
            System.out.println(book1);
        }

    }




}


springboot整合pagehelper

导入相关pom依赖

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

BookMapper


package com.liuxia.springboot02.mapper;

import com.liuxia.springboot02.entity.Book;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BookMapper {
    int deleteByPrimaryKey(Integer bid);

    Book selectByPrimaryKey(Integer bid);

   List<Book> listPage(Book book);

}

BookMapper.xml

 <select id="listPage" resultType="com.liuxia.springboot02.entity.Book" parameterType="com.liuxia.springboot02.entity.Book" >
    select
    <include refid="Base_Column_List" />
    from t_mvc_book
    <where>
      <if test="bname != null and bname !=''">
        and bname like #{bname}
      </if>


    </where>
  </select>

PagerAspect


package com.liuxia.springboot02.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liuxia.springboot02.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
public class PagerAspect {

    @Around("execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable{
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean) param;
                break;
            }
        }

        if (pageBean !=null && pageBean.isPagination())
        PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

        Object proceed = args.proceed(params);

        if (pageBean !=null && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List)proceed);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return proceed;
    }
}

service层

package com.liuxia.springboot02.service;

import com.liuxia.springboot02.entity.Book;
import com.liuxia.springboot02.utils.PageBean;

import java.util.List;

public interface BookService {
    int deleteByPrimaryKey(Integer bid);
    Book selectByPrimaryKey(Integer bid);
    List<Book> listPage(Book book, PageBean pageBean);


}



测试类

 @Test
    public void listPage() {
        Book book = new Book();
        book.setBname("%十里桃花%");
        PageBean pageBean = new PageBean();
        pageBean.setPage(2);
        for (Book book1 : bookService.listPage(book,pageBean)) {
            System.out.println(book1);
        }

2、springboot整合mybatis

over。。。。。