SpringBoot整合Mybatis对单表的增、删、改、查操作
一.目标
SpringBoot整合Mybatis对单表的增、删、改、查操作
二.开发工具及项目环境
IDE: IntelliJ IDEA 2019.3
SQL:Navicat for MySQL
三.基础环境配置
创建数据库:demodb
创建数据表及插入数据
DROP TABLE IF EXISTS t_employee;
CREATE TABLE t_employee (
id int PRIMARY KEY AUTO_INCREMENT COMMENT '主键编号',
name varchar(50) DEFAULT NULL COMMENT '员工姓名',
sex varchar(2) DEFAULT NULL COMMENT '员工性别',
phone varchar(11) DEFAULT NULL COMMENT '电话号码'
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO t_employee VALUES ('1', '张三丰', '男', '13812345678');
INSERT INTO t_employee VALUES ('2', '郭靖', '男', '18898765432');
INSERT INTO t_employee VALUES ('3', '小龙女', '女', '13965432188');
INSERT INTO t_employee VALUES ('4', '赵敏', '女', '15896385278');必备Maven依赖如下:
<!-- MySQL依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.48</version>
</dependency> <!-- Thymleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!-- mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
添加配置文件,可用使用yaml配置,即application.yml(与application.properties配置文件,没什么太大的区别)连接池的配置如下:
spring:
## 连接数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
## jdbc:mysql://(ip地址):(端口号)/(数据库名)?useSSL=false
url: jdbc:mysql://localhost:3306/demodb?useUnicode=true&useSSL=false&characterEncoding=UTF8
## 数据库登录名
data-username: root
## 登陆密码
data-password: ## 静态资源的路径
resources:
static-locations=classpath:/templates/ ## 开启驼峰命名法
mybatis:
configuration:
map-underscor-to-camel-case: true驼峰命名法规范还是很好用的,如果数据库有类似
user_name这样的字段名那么在实体类中可以定义属性为userName(甚至可以写成username,也能映射上),会自动匹配到驼峰属性,如果不这样配置的话,针对字段名和属性名不同的情况,会映射不到。测试配置情况
在java的com包中,新建包controller,在包中创建控制器类:EmployeeController
@Controller
public class EmployeeController{
//测试使用
@GetMapping("/test")
//注解:返回JSON格式
@ResponseBody
public String test() {
return "test";
}
}
启动主程序类,在浏览器中输入:http://localhost:8080/test
四.开始编写
编写ORM实体类
在java的com包中,新建包domain,在包中创建实体类:Employee
public class Employee {
private Integer id; //主键
private String name; //员工姓名
private String sex; //员工性别
private String phone; //电话号码 }
不要忘记封装
完成mapper层增删改查编写
在java的com包中,新建包mapper,在包中创建Mapper接口文件:EmployeeMapper
//表示该类是一个MyBatis接口文件
@Mapper
//表示具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能
@Repository
public interface EmployeeMapper {
//根据id查询出单个数据
@Select("SELECT * FROM t_employee WHERE id=#{id}")
Employee findById(Integer id); //查询所有数据
@Select("SELECT * FROM t_employee")
public List<Employee> findAll(); //根据id修改数据
@Update("UPDATE t_comment SET name=#{name} sex=#{sex} WHERE id=#{id} phone=#{phone}")
int updateEmployee(Employee employee); //添加数据
@Insert("INSERT INTO t_employee(name,sex,phone) values(#{name},#{sex},#{phone})")
public int inserEm(Employee employee); //根据id删除数据
@Delete("DELETE FROM t_employee WHERE id=#{id}")
public int deleteEm(Integer id);
}完成service层编写,为controller层提供调用的方法
在java的com包中,新建包service,在包中创建service接口文件:EmployeeServic
public interface EmployeeService {
//查询所有员工对象
List<Employee> findAll();
//根据id查询单个数据
Employee findById(Integer id);
//修改数据
int updateEmployee(Employee employee);
//添加数据
int addEmployee(Employee employee);
//删除
int deleteEmployee(Integer id);
}
在service包中,新建包impl,在包中创建接口的实现类:EmployeeServiceImpl
@Service
//事物管理
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
//注入EmployeeMapper接口
@Autowired
private EmployeeMapper employeeMapper;
//查询所有数据
public List<Employee> findAll() {
return employeeMapper.findAll();
} //根据id查询单个数据
public Employee findById(Integer id) {
return employeeMapper.findById(id);
} //修改数据
public int updateEmployee(Employee employee) {
return employeeMapper.updateEmployee(employee);
} //添加
public int addEmployee(Employee employee) {
return employeeMapper.inserEm(employee);
} //根据id删除单个数据
public int deleteEmployee(Integer id) {
return employeeMapper.deleteEm(id);
}
}
完成Controller层编写,调用serivce层功能,响应页面请求
在先前创建的controller.EmployeeController中编写方法
@Controller
public class EmployeeController { @Autowired
private EmployeeService employeeService; //主页面
//响应查询所有数据,然后显示所有数据
@GetMapping("/getall")
public String getAll(Model model) {
List<Employee> employeeList = employeeService.findAll();
model.addAttribute("employeeList", employeeList);
return "showAllEmployees";
} //修改页面
//响应到达更新数据的页面
@GetMapping("/toUpdate/{id}")
public String toUpdate(@PathVariable Integer id, Model model){
//根据id查询
Employee employee=employeeService.findById(id);
//修改的数据
model.addAttribute("employee",employee);
//跳转修改
return "update";
} //更新数据请求并返回getall
@PostMapping("/update")
public String update(Employee employee){
//报告修改
employeeService.updateEmployee(employee);
return "redirect:/getall";
} //删除功能
//响应根据id删除单个数据,然后显示所有数据
@GetMapping("/delete/{id}")
public String delete(@PathVariable Integer id){
employeeService.deleteEmployee(id);
return "redirect:/getall";
} //添加页面
//添加数据
@PostMapping("/add")
public String addEmployee(Employee employee){
employeeService.addEmployee(employee);
return "redirect:/getall";
}
}
五.编写前端
主页面
在resouces的templates中,创建主页面:showAllEmployees.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>所有员工信息</title>
</head>
<body>
<h2>所有员工信息</h2>
<table border="1" th:width="400" cellspacing="0">
<tr><th>编号</th><th>姓名</th><th>性别</th><th>电话</th><th>操作</th></tr>
<tr th:each="employee:${employeeList}">
<td th:text="${employee.id}">编号</td>
<td th:text="${employee.name}">姓名</td>
<td th:text="${employee.sex}">性别</td>
<td th:text="${employee.phone}">电话</td>
<td><a th:href="@{'/toUpdate/'+${employee.id}}">修改</a>
<a th:href="@{'/delete/'+${employee.id}}">删除</a></td>
</tr>
</table>
</body>
</html>注意<html lang="en" xmlns:th="http://www.thymeleaf.prg">
修改页面
resouces的templates中,创建修改页面:update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改信息</title>
</head>
<body>
<h2>修改信息</h2>
<form th:action="@{/update}" th:object="${employee}" method="post">
<input th:type="hidden" th:value="${employee.id}" th:field="*{id}">
姓名:<input th:type="text" th:value="${employee.name}" th:field="*{name}"><br>
性别:<input th:type="radio" th:value="男" th:checked="${employee.sex=='男'}" th:field="*{sex}">男
<input th:type="radio" th:value="女" th:checked="${employee.sex=='女'}" th:field="*{sex}">女<br>
电话:<input th:type="text" th:value="${employee.phone}" th:field="*{phone}"><br>
<input th:type="submit" value="更新">
</form> </body>
</html>
添加页面
resouces的templates中,创建添加页面:addEmployee.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.prg">
<head>
<meta charset="UTF-8">
<title>添加员工信息</title>
</head>
<body>
<h2>添加员工信息</h2>
<form action="/add" method="post">
姓名:<input type="text" name="name"><br>
性别:<input type="radio" value="男" name="sex" checked="checked">男
<input type="radio" value="女" name="sex" >女<br>
电话:<input type="text" name="phone"><br>
<input type="submit" value="添加">
</form>
</body>
</html>
启动主程序类,在浏览器中输入:http://localhost:8080/getall
SpringBoot整合Mybatis对单表的增、删、改、查操作的更多相关文章
- MyBatis的配置与使用(增,删,改,查)
---恢复内容开始--- Mybatis入门介绍 一.MyBatis介绍 什么是MyBtis? MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框 ...
- 怎样从C#中打开数据库并进行 增 删 改 查 操作
首先 在C#中引用数据库的操作! (因为我们用的是SQLserver数据库,所以是SqlClient) using System.Data.SqlClient; 1:要实现对数据库的操作,我们必须先登 ...
- 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化. 本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...
- iOS FMDB的使用(增,删,改,查,sqlite存取图片)
iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- django ajax增 删 改 查
具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...
- java实战应用:MyBatis实现单表的增删改
MyBatis 是支持普通 SQL查询.存储过程和高级映射的优秀持久层框架.MyBatis 消除了差点儿全部的JDBC代码和參数的手工设置以及结果集的检索.MyBatis 使用简单的 XML或注解用于 ...
- MVC EF 增 删 改 查
using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
随机推荐
- 吴裕雄--天生自然python机器学习:支持向量机SVM
基于最大间隔分隔数据 import matplotlib import matplotlib.pyplot as plt from numpy import * xcord0 = [] ycord0 ...
- 正则表达式awk学习(三)
awk:格式化文本输出 gawk - pattern scanning and processing language awk:gawk的符号链接 基本用法:gawk [options] 'progr ...
- Python的lambda学习
lambda可以简化简单循环,如下: def fc1(x): return x + 10 print "fc1(23) = ", fc1(23) y = lambda x: x+1 ...
- IO概念和五种IO模型
一.什么是IO? 我们都知道unix世界里.一切皆文件.而文件是什么呢?文件就是一串二进制流而已.不管socket.还是FIFO.管道.终端.对我们来说.一切都是文件.一切都是流.在信息交换的过程中. ...
- CentOS-SendMail服务
title date tags layout music-id CentOS6.5 SendMail服务安装与配置 2018-09-04 Centos6.5服务器搭建 post 456272749 一 ...
- 吴裕雄--天生自然python学习笔记:python设置文档的格式
Win32com 组件可为特定范围的内 容设置格式, 较常用的格式有标题格式.对齐 方式格式及字体格式 . 许多格式使用 常量表示 , 所 以 需先导入 constants常量模块 : 设置标题格式的 ...
- 信息熵、信息增益、信息增益率、gini、woe、iv、VIF
整理一下这几个量的计算公式,便于记忆 采用信息增益率可以解决ID3算法中存在的问题,因此将采用信息增益率作为判定划分属性好坏的方法称为C4.5.需要注意的是,增益率准则对属性取值较少的时候会有偏好,为 ...
- flink分层 api
最底层的processFunction 功能强大,使用复杂 中间层的DataSet api map reduce ...一些基本运算api 中上层的tableAPI 最上层 SQL 两个相似,只是写法 ...
- [LC] 169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appear ...
- OpenCV Canny 边缘检测
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #i ...