Linux公社论坛

 找回密码
 注册
查看: 193|回复: 0

[教程分享] 给一个mybatis-plus的使用教程吧

[复制链接]

1

主题

0

听众

2

积分

新手上路

Rank: 1

uplady 发表于 2020-2-28 15:56:26 |显示全部楼层
1.把之前 mybatis 的dependency删掉改成:
<!--if you want to use mybatis, the first one only use in spring-boot-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <scope>2.1.9</scope>
</dependency>




第一个dependency 用在了 spring-boot框架里,平常只要第二个即可
mybatis-plus的新特性有支持热载,内置分页的很多优点

2. 代码生成:
遇到 Loading class `com.mysql.jdbc.Driver'. This is deprecated.
因为本地的mysql版本高,按照官方要求,更改他的driver
com.mysql.cj.jdbc.Driver 或者:在 mysql-connector-java 的dependency里加上
<version>5.1.37</version>


在mysql5中,jdbc连接mysql5是com.mysql.jdbc.Driver,而mysql6以及以上是com.mysql.cj.jdbc.Driver

附上 generator 的代码
package cn.bysonia.bootmybatisp;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;


public class Generator {
    public static void main(String[] args) {
        // 包名
        String packageName = "cn.bysonia.bootmybatisp";
        boolean serviceNameStartWithI = false;//auth -> UserService, 设置成true: auth -> IUserService
        //把需要自动生成的表 放在这里!!
        generateByTables(serviceNameStartWithI, packageName, "Sonia", "sonia", "person");
        generateByTables(serviceNameStartWithI, packageName, "Sonia", "sonia", "classroom");
        System.out.println("completed...");
    }
    /**
     * @param serviceNameStartWithI
     * @param packageName   包名
     * @param author  作者
     * @param database  数据库名
     * @param tableNames 表名
     */
    private static void generateByTables(boolean serviceNameStartWithI, String packageName, String author, String database, String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        String dbUrl = "jdbc:mysql://127.0.0.1:3306/" + database + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername("root")
                .setPassword("123456")
                .setDriverName("com.mysql.jdbc.Driver");//com.mysql.cj.jdbc.Driver
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(false)
                .setDbColumnUnderline(true)
                .setNaming(NamingStrategy.underline_to_camel)
//              .setSuperMapperClass("cn.saytime.mapper.BaseMapper")
                .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
        config.setActiveRecord(false)
                .setAuthor(author)
                .setOutputDir("C:\\Users\\wengj\\Documents\\codeGen")
                .setFileOverride(true)
                .setEnableCache(false);
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }
        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setController("controller")
                                .setEntity("model")
                                .setMapper("mapper")
                                .setService("service")
                                .setServiceImpl("service.impl")
                                .setXml("mappers")
                ).execute();
    }
}


并且 mapper,service这些文件的生成, 必须也要有 spring-boot-starter-web 的依赖, 不然seviceImpl的类里 @Service的annotation是不会加上的。

<!--webservice restful-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


还有因为 mapper的java类即对标dao层,它的代码生成时并没有mapper的annotation,于是,我们少不了在Application类上加上两个标签




package cn.bysonia.bootmybatisp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;



@SpringBootApplication
@MapperScan("cn.bysonia.bootmybatisp.mapper")
@EnableTransactionManagement
public class BootMybatispApplication {



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



}



附上 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.bysonia.bootMybatisP</groupId>
    <artifactId>boot-mybatisp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-mybatisp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mybatis-plus.version>2.1.9</mybatis-plus.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--webservice restful-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--if you want to use mybatis, the first one only use in spring-boot-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
            <scope>runtime</scope>
      </dependency>
        <!--if you want to use mybatis-plus-generator-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


发现不论 mapper的xml 还是service内容都是空的
  • 代码测试
package cn.bysonia.bootmybatisp;


import cn.bysonia.bootmybatisp.model.Person;
import cn.bysonia.bootmybatisp.service.PersonService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class BootMybatispApplicationTests {
    @Autowired
    PersonService personService;


    @Test
    void contextLoads() {
    }


    @Test
    public void testGetPerson(){
        Person person = personService.selectById(1);
        System.out.println(person);
    }


    @Test
    public void testUpdatePerson(){
        Person person = new Person();
        person.setId(1);
        person.setAge(17);
        personService.updateById(person);
    }


    @Test
    public void testPage(){
        Page<;Person> page = new Page<>();
        page.setCurrent(0);
        page.setSize(3);
        Page<;Person> personPage = personService.selectPage(page);
        System.out.println(JSON.toJSONString(personPage));
    }

}



其中 关于 testPage 还需要 有listener
package cn.bysonia.bootmybatisp;


import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@SpringBootApplication
@MapperScan("cn.bysonia.bootmybatisp.mapper")
@EnableTransactionManagement
public class BootMybatispApplication {


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


   @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

那么上面的pages , total, size等参数的信息又是哪里来的呢
我们不防写一个自己的select

PersonMapper.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="cn.bysonia.bootmybatisp.mapper.PersonMapper">
    <select id="selectPageOwn" parameterType="Map" resultType="cn.bysonia.bootmybatisp.model.Person">
        SELECT  * FROM person
        WHERE 1=1
        <if test="name != null and name !=''">
            AND  name = #{name}
        </if>
    </select>
</mapper>


PersonMapper.java
package cn.bysonia.bootmybatisp.mapper;


import cn.bysonia.bootmybatisp.model.Person;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.plugins.Page;


import java.util.List;
import java.util.Map;


/**
* <p>
*  Mapper 接口
* </p>
*
* @author Sonia
* @since 2020-02-28
*/
public interface PersonMapper extends BaseMapper<;Person> {
    public List<;Person> selectPageOwn(Page<;Person> page, Map<String,Object> params);
}


PersonService.java(注意观察下面的返回参数类型)
package cn.bysonia.bootmybatisp.service;


import cn.bysonia.bootmybatisp.model.Person;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;


import java.util.List;
import java.util.Map;


/**
* <p>
*  服务类
* </p>
*
* @author Sonia
* @since 2020-02-28
*/
public interface PersonService extends IService<;Person> {
    public Page<;Person> selectPageOwn(Page<;Person> page, Map<String,Object> params);
}


PersonServiceImpl.java
package cn.bysonia.bootmybatisp.service.impl;


import cn.bysonia.bootmybatisp.model.Person;
import cn.bysonia.bootmybatisp.mapper.PersonMapper;
import cn.bysonia.bootmybatisp.service.PersonService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;


/**
* <p>
*  服务实现类
* </p>
*
* @author Sonia
* @since 2020-02-28
*/
@Service
public class PersonServiceImpl extends ServiceImpl<;PersonMapper, Person> implements PersonService {


    public Page<;Person> selectPageOwn(Page<;Person> page, Map<String,Object> params){
        List<;Person> persons = baseMapper.selectPageOwn(page, params);
        return page.setRecords(persons);//这时候有了size, total,pages的值
    }
}



小知识~祝你成功~

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

您需要登录后才可以回帖 登录 | 注册

关注Linux公社官方微信,免费领取邀请码。

手机版|Linux公社(LinuxIDC.com)旗下网站【www.linuxidc.net】 ( 浙ICP备07014134号-4 )

GMT+8, 2020-4-6 23:27 , Processed in 1.051061 second(s), 13 queries , Wincache On.

Powered by Discuz! X 3.2

© 2010-2020 Comsenz Inc.

回顶部