1. 程式人生 > >springBoot+mybatisPlus小demo

springBoot+mybatisPlus小demo

專案介紹:採用restful api進行介面規範 / 專案框架SpringBoot+mybatis Plus / 採用mysql進行資料儲存 / 採用swaggerUI進行前後端業務分離式開發。

開發環境:JDK1.8+Mysql8.0.12+IDEAL

實現功能:springboot搭建整體框架,MybatisPlus動態生成Dao+Services+Entity+Controller結構

專案介紹:無實際的業務操作,都是測試功能。其中為了區別mybastis和mybatisPlus,特意寫了兩個介面分別採用mapper.xml進行dao層操作和採用Iservice提供的CRUD操作進行資料查詢。

ps:如果對springboot和mybayisPlus已瞭解,可直接訪問碼雲進行demo下載 https://gitee.com/xc199534/SpringBootMybatisPlus/

----------------------------------------------------------分割線---------------------------------------------

1.專案整體結構

其中Config中包括MybatisPlusConfig和SwaggerConfig兩個類,分別用於初始化MybatisPlus和Swagger基礎設定。

資料庫結構,採用navicat進行視覺化管理。

 

2.配置檔案application.properties

也可採用.yml格式進行配置檔案設定,本專案是使用.properties。

spring.application.name=spring-boot-config
server.port=8080
server.context-path=/

#mybatis mapper檔案的位置
mybatis.mapper-locations=classpath*:mapper/*.xml
#掃描pojo類的位置,在此處指明掃描實體類的包,在mapper中就可以不用寫pojo類的全路徑名了
mybatis.type-aliases-package=com.example.demo
#可以通過mybatis.config-location屬性來指定mybatis的配置檔案的位置,
#mybatis.config-location=classpath:mybatis-config.xml
#資料庫引數設定
jdbc.type=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3.pom.xml內容(所有不上專案完整pom.xml的demo都是耍流氓)

<dependencies>
        <!-- Springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <!-- <version>2.1.3</version>   -->
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <!-- <version>3.0.9</version> -->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- 阿里巴巴druid資料庫連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!-- mysql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- mybatisplus與springboot整合 -->
        <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>2.3</version>
        </dependency>


        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

    </dependencies>

3.自動生成程式碼(Dao/service/Entity)

呼叫MpGenerator.java的主函式生成定義好MVC層結構(MpGenerator定義了檔案位置,檔名稱,依賴關係等屬性)。

Dao層:生成*Dao.java檔案和*Dao.xml,後者可理解為Dao層的資料庫對映操作,mybatis支援在.xml檔案中寫資料庫CURD語句,但myatisPlus支援使用內建的CRUD操作,避免了複雜的資料庫語句。

Service層 :生成一個介面檔案,一個介面實現類。

Entity層:生成實體類,對應到資料庫的表結構。

SchoolDao.java

package com.example.demo.dao;


import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.example.demo.entity.School;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;


public interface SchoolDao extends BaseMapper<School> {
    School getSchoolById(@Param("id") int id);
}
View Code

SchoolService.java

import com.baomidou.mybatisplus.service.IService;
import com.example.demo.entity.School;
import org.elasticsearch.index.query.QueryStringQueryBuilder;

public interface SchoolService extends IService<School> {
    public School getSchoolById(int id);
    // public Iterable<School> searchByES(QueryStringQueryBuilder builder);

}
View Code

SchoolServiceImpl.java

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.example.demo.dao.SchoolDao;
import com.example.demo.entity.School;
import com.example.demo.services.SchoolService;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolDao, School> implements SchoolService {
    @Override
    public School getSchoolById(int id) {
        return baseMapper.selectById(id);
    }
}
View Code

School.java

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import org.springframework.data.elasticsearch.annotations.Document;

import java.io.Serializable;

@TableName("school")
@Document(indexName = "education", type = "school")
public class School implements Serializable {
    @TableId("ID")
    private int id;

    @TableField("NAME")
    private String name;

    @TableField("RANGE")
    private int range;

    @TableField("AGE")
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getRange() { return range; }
    public void setRange(int range) { this.range = range; }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "School{" +
                "id=" + id +
                ", name='" + name +
                ", range=" + range +
                ", age=" + age +
                '}';
    }
}
View Code

4、Controller層

@RestController
@RequestMapping("/")
public class SampleController {
    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private testDao testdao;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @ApiOperation(value = "測試")
    @GetMapping("/home")
    String home() {
        return "Hello World!";
    }

    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public User helloUser() {
        User user = userService.getUserById(1);
        System.out.println(user);
        return user;
    }

    @ApiOperation(value = "採取mybatis方式查詢")
    @ApiImplicitParam(name = "id", value = "使用者id", paramType = "path", required = true)
    @GetMapping("/getSchool/maybatis/{id}")
    public School helloSchool1(@PathVariable("id") int id) {
        School school = schoolService.getSchoolById(id);
        System.out.println(school);
        return school;
    }

    @ApiOperation(value = "採取mybatis-plus方式查詢")
    @ApiImplicitParam(name = "id", value = "使用者id", paramType = "path", required = true)
    @GetMapping("/getSchool/maybatis-plus/{id}")
    public School helloSchool2(@PathVariable("id") int id) {
        School school = schoolService.selectById(id);
        System.out.println(school);
        return school;
    }

    @ApiOperation(value = "插入資料")
    @ApiImplicitParam(name = "school", value = "學校資訊", paramType = "body", required = true)
    @PostMapping("/insert/school")
    public Boolean insertSchool(@RequestBody School school) {
        Boolean tag = schoolService.insert(school);
        System.out.println(tag);
        return tag;
    }
}
View Code

5、呼叫主程式啟動

@SpringBootApplication
@MapperScan("com.example.demo.dao")
@ComponentScan(basePackages = {
        "com.example.demo.config",
        "com.example.demo.controller",
        "com.example.demo.services"})
public class DemoApplication {

    public static void main(String[] args) {

        //System.setProperty("es.set.netty.runtime.available.processors", "false");
        SpringApplication.run(DemoApplication.class, args);
    }
}

 啟動成功後訪問:http://localhost:8080/swagger-ui.html#/,顯示下圖效果即配置成功。