SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuyu19911016520/article/details/81537154

学习一门新技术的时候,以创建demo的试试效果方式,可快速上手,前面的文章临散的说了SpringBoot怎么集成各个开源项目,可能对基础不好的朋友有点吃力,本篇会实现一个基本的示例,方便朋友们快速了解

前面写过项目创建控制器thymeleaf模版数据库连接池mybatis的文章,现在把它们结合起来实现增删改查

本文的源码地址在GitHub上,欢迎下载 expend 项目源码

快速上手

1.pom包里面添加mybatis和thymeleaf的相关包引用
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.1.0</version>
        </dependency>       
2.在application.properties中添加配置
server.port=8001

# thymeleaf配置,开发环境不启用缓存,正式环境下请启用缓存,提高性能
spring.thymeleaf.cache=false
# thymeleaf对html元素格式要求严格,设置它的mode为HTML,忘记结束标签后不会报错
spring.thymeleaf.mode=HTML

# jdbc_config   datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bigdata?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=15000&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hikari will use the above plus the following to setup connection pooling
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=25
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=ExpendHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1

# mybatis 配置
mybatis.mapper-locations=classpath:mapping/*.xml
mybatis.type-aliases-package=com.zypcy.expend.entity
3.启动类,添加mybatis扫描配置
@MapperScan("com.zypcy.expend.dao")
4.创建表与通过generator 生成entity、dao、mybatis xml文件,怎么生成请参考 mybatis详讲
CREATE TABLE customers (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(36) DEFAULT NULL,
  age int(11) DEFAULT NULL,
  is_use tinyint(1) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

生成后的文件结构如下,自动生成CustomerMapper、Customer、CustomerMapper.xml
这里写图片描述
接下来需要在Service里面创建ICustomerService、CustomerServiceImpl,代码如下

public interface ICustomerService {
    //新增
    void add(Customer customer);
    //编辑
    void edit(Customer customer);
    //删除
    void delete(int id);
    //获取单个
    Customer getById(int id);
    //获取所有
    List<Customer> listByAll();
}
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired private CustomerMapper customerMapper;

    @Override
    public void add(Customer customer) {
        customerMapper.insert(customer);
    }

    @Override
    public void edit(Customer customer) {
        customerMapper.updateByPrimaryKey(customer);
    }

    @Override
    public void delete(int id) {
        customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Customer getById(int id) {
        return customerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Customer> listByAll() {
        return customerMapper.listByAll();
    }
}
5.创建CustomerController与thymeleaf的模版页面
@Controller
@RequestMapping("customers")
public class CustomerController {

    @Autowired private ICustomerService customerService;

    @RequestMapping("list")
    public String list(ModelMap map){
        map.addAttribute("customers",customerService.listByAll());
        return "customer/list";
    }

    @RequestMapping("edit")
    public String edit(ModelMap map, @RequestParam(defaultValue = "0") int id){
        //isAdd : 向前端页面返回一个是新增与编辑的标识
        if(id > 0){
            map.addAttribute("isAdd",false);
            map.addAttribute("customer",customerService.getById(id));
        }else{
            map.addAttribute("isAdd",true);
            map.addAttribute("customer",new Customer());
        }
        return "customer/edit";
    }

    //新增和编辑
    @ResponseBody
    @RequestMapping("save")
    public String save(@ModelAttribute Customer customer){
        if(customer == null){
            return "fail";
        }
        if(customer.getId() != null && customer.getId() > 0){
            customerService.edit(customer);
        }else{
            customerService.add(customer);
        }
        return "success";
    }
}

在resources - templates 下添加 customer 文件夹目录,再在customer下添加 list.html、edit.html页面,页面内容如下:
list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户列表</title>
    <style>
        table{border-collapse:collapse;}
        table,th, td{border: 1px solid black;padding: 5px;text-align: center;}
    </style>
</head>
<body>
    <br/>
    <br/>
    <a href="/customers/edit">新增用户</a>
    <br/>
    <br/>
    <table>
        <thead>
            <th width="20%">id</th>
            <th width="20%">name</th>
            <th width="20%">age</th>
            <th width="20%">isUse</th>
            <th width="20%">操作</th>
        </thead>
        <tbody>
            <tr th:each="customer : ${customers}">
                <td th:text="${customer.id}"></td>
                <td th:text="${customer.name}"></td>
                <td th:text="${customer.age}"></td>
                <td th:text="${customer.isUse}"></td>
                <td>
                    <a th:href="@{/customers/edit(id=${customer.id})}">编辑</a> &nbsp;&nbsp;
                    <a th:href="@{/customers/del/{id}(id=${customer.id})}">删除</a>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增、编辑客户</title>
</head>
<body>
    <form th:action="@{/customers/save}" method="post">

        <div th:if="${isAdd} == false">
            <label>id</label>
            <input type="text" name="id" readonly="readonly" th:field="${customer.id}" />
        </div>
        <div>
            <label>name</label>
            <input type="text" name="name" th:field="${customer.name}" />
        </div>
        <div>
            <label>age</label>
            <input type="text" name="age" th:field="${customer.age}" />
        </div>
        <div>
            <label>isUse</label>
            <input type="text" name="isUse" th:field="${customer.isUse}" />
        </div>
        <div>
            <input type="submit" value="提交" />
        </div>
    </form>
</body>
</html>
6.启动项目,访问 http://localhost:8001/customers/list ,进行新增、编辑、删除操作

这里写图片描述
这里写图片描述

到此,增删改查示例代码就全部写完了,里面用到很多内容

猜你喜欢

转载自blog.csdn.net/zhuyu19911016520/article/details/81537154