一.目標
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