SpringBoot集成thymeleaf增删改查示例

有小伙伴找我要个 thymeleaf 的 demo,说自己集成的总是报错,所以就有了这篇...

关于什么是 thymeleaf 我就不赘述了,相信搜到这篇的大部分是奔着如何集成来的。

本文源码先附上:https://gitee.com/niceyoo/springboot-thymeleaf-demo

懒得看下文的可直接跳转至源码。下面把一些主要的配置粘一下,不做额外赘述,大部分可以在上方源码中获取,尤其是前端部分。

1、本文环境

  • IDEA,2021.2
  • JDK,8
  • SpringBoot,2.4.4
  • MybatisPlus,3.1.1
  • Thymeleaf,2.4.4
  • layui,2.5.6

2、依赖环境(pom.xml)

直接用的 spring-boot-starter-parent,不了解的可以看下这篇文章: https://www.cnblogs.com/niceyoo/p/10960207.html

主要依赖有:druid连接池、mybatisplus、mysql驱动、thymeleaf依赖。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.4</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--web-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--新增durid监控-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.23</version>
    </dependency>
    <!--Mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus</artifactId>
        <version>3.1.1</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.1.1</version>
    </dependency>
    <!-- mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
    <!--thymeleaf-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3、配置文件(application.yaml)

主要定义了 数据库、thymeleaf、mybatisplus配置。

server:
  port: 8089

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/thymeleaf-db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
  thymeleaf:
    #模板的模式,支持 HTML, XML TEXT JAVASCRIPT
    mode: HTML5
    #编码 可不用配置
    encoding: UTF-8
    #内容类别,可不用配置
    content-type: text/html
    #开发配置为false,避免修改模板还要重启服务器
    cache: false
    #配置模板路径,默认是templates,可以不用配置
    prefix: classpath:/templates
    suffix: .html

mybatis-plus:
  typeAliasesPackage: com.thymeleaf.demo.com.thymeleaf.demo.entity
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true
    lazyLoadingEnabled: true
    multipleResultSetsEnabled: true
    #这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

用到的SQL:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(32) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `nick_name` varchar(64) DEFAULT NULL,
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

4、MyBatisPlus配置类(可忽略)

mybatisplus配置类,设置扫描包、加入分页插件。在 mybatisplus 3.4版本之后 PaginationInterceptor 弃用了,改用 MybatisPlusInterceptor,不了解的可自行搜索。至于为什么要使用自定义分页插件可参考方法注释解释。

@EnableTransactionManagement
@Configuration
@MapperScan("com.thymeleaf.demo.dao")
public class MyBatisPlus {

    /**
     * myabtis 实现的分页为什么还要分页插件?
     * <p>
     * 1.mybatis实现得分页时逻辑分页或者叫做内存不是物理分页
     * 2.他是把符合条件的数据全部查询出来放到内存中,然后返回你需要的那部分
     * 3.表中数据不多时,可以使用,速度慢一些;当数据量大时,建议使用物理分页
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
      return new PaginationInterceptor();
    }

}

5、控制层(UserController)

如下写了个增删改查的实例,没有按照代码规范来,大致看一下即可。

其中返回 ModelAndView 的方法是用来映射对应的前端页面的,返回 R 的方法是接口返回形式。其中 R 是 mybatisplus 中提供的一个返回给前端信息的工具类,为了方便直接拿来用了。

@RestController
@RequestMapping("user")
public class UserController extends ApiController {

    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 用户列表展示
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    @GetMapping("view")
    public ModelAndView view(){
        return new ModelAndView("/user").addObject("modelName","用户管理模块");
    }

    /**
     * 新增用户
     *
     * @param user 用户实体
     * @return 新增结果
     */
    @PostMapping("insert")
    public R insert(@RequestBody User user){
        Assert.notNull(user,"user不能为空");
        return success(userService.save(user));
    }

    /**
     * 修改用户
     *
     * @param user 用户实体
     * @return 修改结果
     */
    @PostMapping("update")
    public R update(@RequestBody User user){
        Assert.notNull(user,"user不能为空");
        return success(userService.saveOrUpdate(user));
    }

    /**
     * 删除用户
     *
     * @param ids 用户ids
     * @return 删除结果
     */
    @PostMapping("delete")
    public R delete(@RequestParam List<String> ids){
        Assert.notNull(ids,"ids不能为空");
        return success(userService.removeByIds(ids));
    }

    /**
     * 查询用户数据 - 分页
     *
     * @param current 当前页
     * @param size 页码大小
     * @return 分页数据列表
     */
    @GetMapping("selectAll")
    public R selectAll(@RequestParam Integer current, @RequestParam Integer size, @RequestParam(required = false) String userName){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(userName)){
            queryWrapper.like("user_name", userName);
        }
        Page<User> page = new Page<User>(current,size);
        IPage<User> result = userService.page(page, queryWrapper);
        return success(result);
    }
}

6、service服务层

服务层就比较简单了,直接用的 mybatisplus 的 IService,这个类中实现了大部分方法。直接拿来集成就好了,代码都不用写。

public interface UserService extends IService<User> {}

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {}

一个接口,一个实现,没写一点代码。

7、前端界面

前端界面用的 layui,全部代码就不粘贴了,说一下 Thymeleaf 吧,主要是头部需要声明,结构如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}"/>
    </head>
    <body>
        <div>测试</div>
    </body>
</html>

本文源码:https://gitee.com/niceyoo/springboot-thymeleaf-demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章