爆肝万字长文,深入总结springboot整合mybatis,一次性带你搞懂!

449 阅读1分钟

demo样式

个人整理了一些资料,有需要的朋友可以直接点击领取。

Java基础知识大全

22本Java架构师核心书籍

从0到1Java学习路线和资料

1000+道2021年最新面试题

搭建环境(pom文件)

项目创建

在创建项目时,应当选择web、thymeleaf、mybatis(我这边是阿里云的镜像,所以都是中文选项,自己可以对号入座)

我使用阿里云的镜像选择之后还是要自己手动导入thymeleaf(如果使用官网的应该没有这个bug)

注意:选择JDBC时,如果不进行配置文件中数据库配置,程序会报错(dataSource连接不成功什么的),所以一般不使用mybatis时,不选JDBC,自己手动配置比较好

导入依赖和插件

依赖

在项目已经创建好的基础上,还需要加入下列依赖(我前面说了,thymeleaf依赖可能创建后就有了),这里我用的druid连接池,你也可以用原生的(只要配置文件中对应好就行)

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.3.7.RELEASE</version>
        </dependency>
        <!--druid连接池依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

        <!--数据库驱动-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

插件

generator插件

configurationFile表示generator配置文件路径(一般放在resources下)

 <!--配置generator插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                </dependencies>
                <!--指定配置文件路径-->
                <configuration>
                    <configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>

资源拷贝插件

这个地方我踩过坑,java目录中主要就是配置的mapper中xml,下边是resources中文件,千万不要忘了配置html

 <!--配置资源拷贝插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.html</include>
                </includes>
            </resource>
        </resources>

配置文件

application.properties

下边注释是mybatis的一些其他配置(不使用generator时可能会用到)

spring.datasource.url= jdbc:mysql://localhost:3306/login?useUnicode=true&characterEncoding=utf-8&useSSl=false
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.username= root
spring.datasource.password= wityy
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource



# 应用服务 WEB 访问端口
#server:
#  port: 8080
#
#
#下面的配置对于本项目是不需要的
#
#  下面这些内容是为了让MyBatis映射
#  指定Mybatis的Mapper文件
#mybatis:
#  扫描classpath中mapper目录下的映射配置文件,当映射配置文件放在resources目录下使用该配置
#  如果映射配置文件放在mapper包中不用使用该配置
#  mapper-locations:
#    - classpath:/mapper/*.xml
#  resultType 设置pojo类简写,generator插件生成的不需要配置,如果自己写的话可以进行配置
#  type-aliases-package: cn.wit.springbootmybatis.pojo

generatorConfig.xml

这里要注意的是,导入这个dtd时会报红,需要设置一下dtd,在setting中设置

targetPackage根据项目中的包名决定

<?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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!--是否去除自动生成的注释-->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/login"
                        userId="root"
                        password="wityy"
        ></jdbcConnection>
        <!--默认false,把JDBC DECIMAL和NUMERIC类型解析为Integer
        NUMRIC类型解析为java.math.BigDecimal-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>



        <javaModelGenerator targetPackage="cn.wit.springbootmybatis.pojo"
                            targetProject=".\src\main\java">
            <!--enableSubPackages:是否让schema作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
            <!--从数据库返回的值被清理前后的空格-->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--targetProject:mapper映射文件生成的位置-->
        <sqlMapGenerator targetPackage="cn.wit.springbootmybatis.mapper"
                         targetProject=".\src\main\java">
            <!--enableSubPackages:是否让schema作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.wit.springbootmybatis.mapper"
                             targetProject=".\src\main\java">
            <!--enableSubPackages:是否让schema作为包的后缀-->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!--指定数据库表-->
        <table tableName="flower"></table>
    </context>
</generatorConfiguration>

配置完generator之后,生成pojo和mapper,maven双击红框

然后就会生成这样的结构,可以看到里边有一个FlowerExample,它的作用是设置限定条件的(我之前也没学过generator,这里就只写这个demo用到的)

启动函数

加上@MapperScan(“cn.wit.springbootmybatis.mapper”)注解

@SpringBootApplication
@MapperScan("cn.wit.springbootmybatis.mapper")//指定扫描接口与映射配置文件包名
public class SpringbootmybatisApplication {

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

}

service

public interface FlowerService {
    //增一个
    void addFlower(Flower flower);
    //删一个
    void delFlower(int id);
    //查全部
    List<Flower> selAllFlower();
    //改一个
    void updPriceFlower(Flower flower);
    //预更新
    Flower preUpdateFlower(int id);

}


当要查询时,selectByExample将example作为参数表示查询全部(如果想加入限定条件,example.createCriteria().andNameEqualTo(name);对exmple进行设置) 可以看到删除等其他操作都可以根据Example进行限定设置,这个用到的时候再度娘吧

相比我那篇未整合mybatis的文章,那个的更新逻辑是传递id和price,只对该id对应数据price进行更改 这篇的逻辑稍微改了一下,就是通过id拿到整条数据,更改该数据price,然后将这条数据更新到数据库(这样更符合generator的使用,因为它updateByPrimaryKey方法根据id进行更新整条数据,而不是单个属性,不过这个也可以根据example进行实现)

@Service
public class FlowerServiceImpl implements FlowerService {
    @Autowired
    FlowerMapper flowerMapper;

    @Override
    @Transactional
    public void addFlower(Flower flower) {
        this.flowerMapper.insert(flower);
    }

    @Override
    @Transactional
    public void delFlower(int id) {
        this.flowerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Flower> selAllFlower() {
        FlowerExample example=new FlowerExample();
        return this.flowerMapper.selectByExample(example);
    }

    @Override
    @Transactional
    public void updPriceFlower(Flower flower) {
        this.flowerMapper.updateByPrimaryKey(flower);
    }

    @Override
    public Flower preUpdateFlower(int id) {
        return this.flowerMapper.selectByPrimaryKey(id);
    }


}


Controller

PageController

页面跳转,会优先匹配其他的url,当其他匹配不上时,会匹配这个,然后认为它是html页面请求

@Controller
public class PageController {
    /**
     * 页面跳转功能
     */

    @RequestMapping("/{page}")
    public String showPage(@PathVariable("page") String page){
        return page;
    }
}


FlowerController


@Controller
@RequestMapping("flower")
public class FlowerController {
    @Autowired
    private FlowerService flowerService;


    /*
    * 增加数据
    * */
    @RequestMapping("/addFlower")
    public String addFlower(Flower flower, HttpServletRequest request){

        try {
            this.flowerService.addFlower(flower);   //将该flower添加
            return "redirect:/flower/show";  //添加后重定向主界面
        }catch (Exception e){
            return "error";
        }
    }

    /*
    * 删除对应id数据
    * */
    @RequestMapping("/delFlower/{id}")
    public String delFlower(@PathVariable int id, HttpServletRequest request){

        try {
            this.flowerService.delFlower(id);
            return "redirect:/flower/show";
        }catch (Exception e){
            return "error";
        }
    }

    /*
    * 展示主界面
    * */
    @RequestMapping("/show")
    public String selAllFlower(HttpServletRequest request){
        try {
            List<Flower> list = this.flowerService.selAllFlower();
            request.setAttribute("flowers",list);
            return "main.html";
        }catch (Exception e){
            return "error.html";
        }

    }



    /*
     *
     * 更新处理
     */
    @RequestMapping("/updPriceFlower")
    public String updPriceFlower(Flower flower,HttpServletRequest request){
        try {
            Flower flower1=this.flowerService.preUpdateFlower(flower.getId());
            flower1.setPrice(flower.getPrice());
            this.flowerService.updPriceFlower(flower1);
            return "redirect:/flower/show";   //重定向到主页面
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }

    }

    /*
     *
     * 预更新,准备跳转到updFlower界面,该页面请求updPriceFlower
     */
    @RequestMapping("/update/{id}")
    public String update(@PathVariable int id, HttpServletRequest request){
        try {
            request.setAttribute("id",id);
            return "updFlower";
        }catch (Exception e){
            return "error";
        }

    }


}


thymeleaf

error

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>ERROR</h1>
ERROR
</body>
</html>

main

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}">

<head>
    <meta charset="UTF-8">
    <title>花卉信息</title>
</head>
<body>
<table border="1px">
    <tr>
        <th>编号</th>
        <th>花名</th>
        <th>价格</th>
        <th>产地</th>
        <th>价格更新</th>
        <th>删除</th>
    </tr>
    <tr th:each="flower : ${flowers}">
        <td th:text="${flower.id}"></td>
        <td th:text="${flower.name}"></td>
        <td th:text="${flower.price}"></td>
        <td th:text="${flower.production}"></td>
        <td>
            <a th:href="@{/flower/update/{id}/(id=${flower.id})}">更新</a>
        </td>
        <td>
            <a th:href="@{/flower/delFlower/{id}/(id=${flower.id})}">删除</a>
        </td>
    </tr>

</table>


<br><br>
添加花卉
<form th:action="@{/flower/addFlower}" method="get">
    输入name<input type="text" value="" name="name"><br>
    输入单价<input type="text" value="" name="price"><br>
    输入产地<input type="text" value="" name="production"><br>
    <input type="submit" value="提交">

</form>
</body>
</html>

updFlower

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/flower/updPriceFlower" method="get">
    请输入更新价格<input type="text" name="price"><br>
    <input type="hidden" name="id" th:value="${id}">
    <input  type="submit" value="提交">
</form>
</body>
</html>