SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客

沙海
沙海
沙海
1017
文章
2
评论
2021年4月27日04:05:30
评论
1 6133字阅读20分26秒
摘要

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

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

SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客

闪耀的瞬间
2018-08-14 10:43:35
SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客
8399

SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客

收藏

19

分类专栏:
spring boot
java
SpringBoot 项目开发
文章标签:
spring boot

版权

SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客

学习一门新技术的时候,以创建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>		
1234567891011121314151617181920212223

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
1234567891011121314151617181920212223242526

3.启动类,添加mybatis扫描配置

@MapperScan("com.zypcy.expend.dao")

12

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;
1234567

生成后的文件结构如下,自动生成CustomerMapper、Customer、CustomerMapper.xml SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客 接下来需要在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();
}

12345678910111213
@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();
    }
}
123456789101112131415161718192021222324252627282930

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";
    }
}
12345678910111213141516171819202122232425262728293031323334353637383940

在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>
123456789101112131415161718192021222324252627282930313233343536373839

thymeleaf生成a标签链接地址 1.如果想在路径中加入参数? @{/files/view(id=${file.id})} ,thymeleaf会在前端渲染成?id=xxx。当多个参数时,以逗号分隔,写成(id=xxx,name=xxx) 效果:/files/view?id=xxx

2.restful形式 @{/files/view/{id}(id=${file.id})} 效果:/files/view/xxx

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>
12345678910111213141516171819202122232425262728293031

######6.启动项目,访问 http://localhost:8001/customers/list ,进行新增、编辑、删除操作 SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客 SpringBoot项目开发(十六):springboot+mybatis+thymeleaf增删改查_zhuyu19911016520-CSDN博客

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

下篇 pagehelper翻页

继续阅读
weinxin
资源分享QQ群
本站是一个IT技术分享社区, 会经常分享资源和教程; 分享的时代, 请别再沉默!
沙海
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: