之前一直都是使用了mybatis-plus,因为项目的需要突然要使用mybatis进行整合,就写篇文章温习一下!
技术栈及工具:
mysql 8
mybatis
sping boot
Java 8
IDEA
构建项目
创建一个空工程,方便以后学习其它框架,不用东一个项目右一个项目
创建好之后会弹出来Project Structure窗口点击+号创建项目架构
项目名称见名之意随便起,但是在真实的项目中都是以公司的名称倒过来进行编写
勾选依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.guhaoqaun</groupId>
<artifactId>01-springboot-myabtis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>01-springboot-myabtis</name>
<description>Spring Boot集成Mybatis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- web,可以理解成controller层的请求映射 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok插件,用于生成get,set方法或有参无参构造 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 测试,不用,留在这为了好看 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
编写配置
选中生成的application.properties文件ctrl + F6重命名
application中的数据库url 三条///表示为本地 localhost == ///
#端口号
server:
port: 8080
servlet:
#前缀
context-path: /
#数据库名及时区
spring:
datasource:
url: jdbc:mysql:///test?serverTimezone=GMT%2B8&characterEncoding=utf8
username: root
password: root
mybatis:
configuration:
default-statement-timeout: 30
map-underscore-to-camel-case: true
mapper-locations:
- classpath:/mapper/*.xml
#日志
logging:
level:
com.guhaoquan: debug
数据库表
实现使用mybatis进行CRUD
实体类
package com.guhaoqaun.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 生成的实体类尽量与数据库字段一一对应
* @Data 生成get set方法
* @NoArgsConstructor 无参构造
* @AllArgsConstructor 有参构造
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id; //用户id
private String name;//用户名称
private Integer age; //用户年龄
private String email; //用户邮箱
}
统一返回值类型
这个可以拿来直接在项目中使用,现在很多公司命名为R(具体看业务需要)
package com.guhaoqaun.utils;
import lombok.Data;
import java.io.Serializable;
@Data
public class JsonResult implements Serializable {
private static final long serialVersionUID = -7075739518556671717L; //序例化
private int state = 1;//状态码
private String message = "ok";//1:表示SUCCESS,0:ERROR
private Object data;//正确数据
public JsonResult(){}
public JsonResult(String message){
this.message=message;
}
//一般查询时调用。用于封装数据
public JsonResult(Object data){
this.data=data;
}
//出现异常时调用
public JsonResult(Throwable t){
this.state=0;
this.message=t.getMessage();
}
}
自定义异常
package com.guhaoqaun.utils;
public class ServiceException extends RuntimeException{
private static final long serialVersionUID = -5614175354004336252L;
public ServiceException(){
super();
}
public ServiceException(String message){
super(message);
}
public ServiceException(Throwable cause){
super(cause);
}
}
查询数据表中的所有数据
dao
package com.guhaoqaun.dao;
import com.guhaoqaun.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper //mybatis注解,声明这是一个接口对应类
public interface StudentDao {
/**
* 使用List集合封装所有的数据
* @return 从数据库中查询到的数据
*/
List<Student> selectStudent();
}
Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.guhaoqaun.dao.StudentDao">
<!-- namespace:必须有值,自定义的唯一字符串推荐使用:dao 接口的全限定名称 -->
<!--
<select>: 查询数据, 标签中必须是 select 语句
id: sql 语句的自定义名称,推荐使用 dao 接口中方法名称,
使用名称表示要执行的 sql 语句
resultType: 查询语句的返回结果数据类型,使用全限定类名
-->
<!-- sql语句,查询所有数据,实际项目中不能用*,把字段写出来 -->
<select id="selectStudent" resultType="com.guhaoqaun.entity.Student">
select id,name,age,email from t_student
</select>
</mapper>
service
package com.guhaoqaun.service;
import com.guhaoqaun.entity.Student;
import java.util.List;
public interface StudentService {
/**
* 用户访问的方法
* @return
*/
List<Student> selectStudentList();
}
serviceImpl
package com.guhaoqaun.service.impl;
import com.guhaoqaun.dao.StudentDao;
import com.guhaoqaun.entity.Student;
import com.guhaoqaun.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
/* 引入dao层的方法接口 */
@Autowired
private StudentDao studentDao;
/**
* 实现业务逻辑
* @return
*/
@Override
public List<Student> selectStudentList() {
List<Student> list = studentDao.selectStudent(); //调用dao层的方法,返回List集合,dao与service层的返回类型须统一
return list;
}
}
controller
package com.guhaoqaun.controller;
import com.guhaoqaun.service.StudentService;
import com.guhaoqaun.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("student")
@RestController
public class StudentController {
/* 引入service */
@Autowired
private StudentService studentService;
/**
* 查询列表
* @return
*/
@RequestMapping("list")
public JsonResult list(){
return new JsonResult(studentService.selectStudentList());
}
}
测试
localhost:8080/student/list
当前后端分离时可以把这个路径给到前端即可
新增数据
dao
/**
* 返回值使用int,如新增成功返回新增条数,失败则返回0
* @param entity
* @return
*/
int insertStudent(Student entity);
mapper.xml
<insert id="insertStudent">
insert into t_student(id,name,age,email)
values
(#{id},#{name},#{age},#{email})
</insert>
service
/**
* 用户访问新增方法
* @param entity
* @return
*/
int insertStudents(Student entity);
serviceimpl
@Override
public int insertStudents(Student entity) {
if (entity == null)
throw new ServiceException("保存对象不能为空");
if (StringUtils.isEmpty(entity.getEmail()))
throw new ServiceException("保存对象名称不能为空");
int insertStudent = studentDao.insertStudent(entity);
return insertStudent;
}
controller
/**
* 用户新增
* @param entity
* @return
*/
@RequestMapping("save")
@ResponseBody
public JsonResult save(Student entity){
studentService.insertStudents(entity);
return new JsonResult("保存成功");
}
测试
localhost:8080/student/save?name=bbbb&age=21&[email protected]
查看数据库
修改数据库中的方法
dao
/**
* 修改用户数据,如成功返回条数,失败则返回0
* @param entity
* @return
*/
int updatestudent(Student entity);
mapper.xml
<update id="updatestudent">
update t_student set
name=#{name},
age=#{age},
email=#{email}
where id=#{id}
</update>
service
/**
* 用户访问修改方法
* @param entity
* @return
*/
int updatestudent(Student entity);
serviceImpl
@Override
public int updatestudent(Student entity) {
//参数校验
if (entity.getId() == null || entity.getId() < 0)
throw new ServiceException("请选择一条记录进行修改");
int updatestudent = studentDao.updatestudent(entity);
if (updatestudent < 0)
throw new ServiceException("修改失败,请填写相关参数");
return updatestudent;
}
controller
@RequestMapping("update")
public JsonResult update(Student entity){
studentService.updatestudent(entity);
return new JsonResult("修改成功");
}
测试
localhost:8080/student/update?id=7&name=bccb&age=21&[email protected]
删除用户数据
dao
/**
* 删除用户数据
* @param id
* @return
*/
int deleteStudent(Integer id);
mapper.xml
<delete id="deleteStudent">
delete from t_student where id=#{id}
</delete>
service
/**
* 用户访问删除方法
* @param id
* @return
*/
int deleteStudent(Integer id);
serviceImpl
@Override
public int deleteStudent(Integer id) {
if (id == null || id < 0)
throw new ServiceException("请选择一条数据进行删除");
int student = studentDao.deleteStudent(id);
if (student == 0)
throw new ServiceException("此记录可能已经不存在了");
return student;
}
controller
@RequestMapping("delete")
public JsonResult delete(Integer id){
studentService.deleteStudent(id);
return new JsonResult("删除成功");
}
测试
http://localhost:8080/student/delete?id=7