springboot(七)整合mybatis

58 阅读2分钟

pom.xml

引入依赖

pom.xml

        <!--数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <!-- 集成mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- 集成mysql连接 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--分页-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.6</version>
        </dependency>

引入插件

pom.xml

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.0</version>
                <configuration>
                    <configurationFile>src/main/resources/generator.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.22</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

增加自动生成配置文件

src/main/resource/generator.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>
    <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">

        <!-- 自动检查关键字,为关键字增加反引号 -->
        <property name="autoDelimitKeywords" value="true"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!--覆盖生成XML文件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        <!-- 生成的实体类添加toString()方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <!-- 不生成注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 配置数据源,需要根据自己的项目修改 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/springboot2?serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!-- domain类的位置 targetProject是相对pom.xml的路径-->
        <javaModelGenerator targetProject="src/main/java"
                            targetPackage="com.example.springboot2.pojo"/>

        <!-- mapper xml的位置 targetProject是相对pom.xml的路径 -->
        <sqlMapGenerator targetProject="src/main/resources"
                         targetPackage="mapper"/>

        <!-- mapper类的位置 targetProject是相对pom.xml的路径 -->
        <javaClientGenerator targetProject="src/main/java"
                             targetPackage="com.example.springboot2.mapper"
                             type="XMLMAPPER"/>
        <!--数据库中的user表-->
        <table tableName="user" domainObjectName="User"/>
    </context>
</generatorConfiguration>

maven插件自动生成pojo,mapper

image.png

application.yml配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot2?serverTimezone=UTC
    username: root
    password: 123456

mybatis:
  type-aliases-package: com.example.springboot2.pojo
  mapper-locations: classpath:/mapper/*Mapper.xml

主入口增加map

@MapperScan

package com.example.springboot2;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@MapperScan("com.example.springboot2.mapper")
public class Springboot2Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot2Application.class, args);
    }
}

测试

service

package com.example.springboot2.service;

import com.example.springboot2.mapper.UserMapper;
import com.example.springboot2.pojo.User;
import com.example.springboot2.pojo.UserExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    @Resource
    private UserMapper userMapper;
    public Object queryList(Map<String, Object> req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(req.containsKey("name")){
            String name = (String) req.get("name");
            criteria.andNameEqualTo(name);
        }

        List<User> list = userMapper.selectByExample(userExample);

        PageHelper.startPage(1, 10);

        PageInfo<User> pageInfo = new PageInfo<>(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("total",pageInfo.getTotal());
        return map;
    }

    public void insert(User user) {
        userMapper.insert(user);
    }

    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    public void delete(Integer id) {
        userMapper.deleteByPrimaryKey(id);
    }
}

controller

package com.example.springboot2.controller;

import com.example.springboot2.pojo.User;
import com.example.springboot2.service.UserService;
import com.example.springboot2.util.JSONResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
    @GetMapping("list")
    public JSONResult userList(@RequestBody Map<String, Object> req) {
        return JSONResult.ok(userService.queryList(req));
    }

    @PostMapping("/insert")
    public JSONResult insert(@RequestBody User user) {
        userService.insert(user);
        return JSONResult.ok();
    }

    @PutMapping("/update")
    public JSONResult update(@RequestBody User user) {
        userService.update(user);
        return JSONResult.ok();
    }

    @DeleteMapping("/delete/{id}")
    public JSONResult update(@PathVariable Integer id) {
        userService.delete(id);
        return JSONResult.ok();
    }
}

postman测试

查询

image.png

image.png

修改

image.png

新增

image.png

删除

image.png

自定义mybatis

查询学生成绩

mybatis自动生成,只能单表,所有连表查询一般需要自己写

修改mybatis扫描xml位置

application.yml

mybatis:  
    mapper-locations: classpath:/mapper/**/*.xml

resp

resp/StudentScoreResp

package com.example.springboot2.resp;

import lombok.Data;
import javax.validation.constraints.NotBlank;

@Data
public class StudentScoreResp {
    private String sId;

    @NotBlank(message = "username不能为空")
    private String sName;

    private String sSex;

    private String cName;

    private String scScore;
}

自定义xml

resource/mapper/cust/StudentScoreMapperCust.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.example.springboot2.mapper.cust.StudentScoreMapperCust">

    <resultMap id="studentScoreMap" type="com.example.springboot2.resp.StudentScoreResp">
        <result property="sId" column="s_id"/>
        <result property="sName" column="s_name"/>
        <result property="sSex" column="s_sex"/>
        <result property="cName" column="c_name"/>
        <result property="scScore" column="s_score"/>
    </resultMap>

    <select id="selectSCust" resultMap="studentScoreMap">
        select s.s_id,s.s_name,s.s_name,s.s_sex,c.c_name,sc.s_score
        from student s
                 left join score sc on s.s_id = sc.s_id
                 left join course c on c.c_id = sc.c_id
    </select>
</mapper>


自定义mapper

mapper/cust/StudentScoreMapperCust

package com.example.springboot2.mapper.cust;

import com.example.springboot2.resp.StudentScoreResp;

import java.util.List;

public interface StudentScoreMapperCust {
    List<StudentScoreResp> selectSCust();

}

service

package com.example.springboot2.service;

import com.example.springboot2.mapper.cust.StudentScoreMapperCust;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class StudentScoreService {
    @Resource
    private StudentScoreMapperCust studentScoreMapperCust;
    public Object queryList() {
        return studentScoreMapperCust.selectSCust();
    }
}

controller

package com.example.springboot2.controller;

import com.example.springboot2.service.StudentScoreService;
import com.example.springboot2.service.UserService;
import com.example.springboot2.util.JSONResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("student")
public class StudentController {
    @Resource
    private StudentScoreService studentScoreService;
    @GetMapping("query-list")
    public JSONResult queryList(){
        return JSONResult.ok(studentScoreService.queryList());
    }
}


测试

image.png