微信公众号:一个优秀的废人 若有问题或建议,请后台留言,我会尽力解决你的问题。php
如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,本文经过注解的形式实现。前端
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎全部的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 能够对配置和原生 Map 使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。java
优势:mysql
缺点:git
sql 语句,建立表,插入数据:github
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `student` VALUES ('1', 'aaa', '21');
INSERT INTO `student` VALUES ('2', 'bbb', '22');
INSERT INTO `student` VALUES ('3', 'ccc', '23');
复制代码
<?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 http://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.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nasus</groupId>
<artifactId>mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis</name>
<description>mybatis Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 启动 web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- mysql 链接类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid 数据库链接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!-- lombok 插件 用于简化实体代码 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
复制代码
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
复制代码
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
}
复制代码
使用了 lombok 简化了代码。web
import com.nasus.mybatis.domain.Student;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface StudentMapper {
@Insert("insert into student(name, age) values(#{name}, #{age})")
int add(Student student);
@Update("update student set name = #{name}, age = #{age} where id = #{id}")
int update(@Param("name") String name, @Param("age") Integer age, @Param("id") Integer id);
@Delete("delete from student where id = #{id}")
int delete(int id);
@Select("select id, name as name, age as age from student where id = #{id}")
Student findStudentById(@Param("id") Integer id);
@Select("select id, name as name, age as age from student")
List<Student> findStudentList();
}
复制代码
这里有必要解释一下,@Insert 、@Update、@Delete、@Select 这些注解中的每个表明了执行的真实 SQL。 它们每个都使用字符串数组 (或单独的字符串)。若是传递的是字符串数组,它们由每一个分隔它们的单独空间串联起来。这就当用 Java 代码构建 SQL 时避免了“丢失空间”的问题。 然而,若是你喜欢,也欢迎你串联单独 的字符串。属性:value,这是字符串 数组用来组成单独的 SQL 语句。算法
@Param 若是你的映射方法的形参有多个,这个注解使用在映射方法的参数上就能为它们取自定义名字。若不给出自定义名字,多参数(不包括 RowBounds 参数)则先以 "param" 做前缀,再加上它们的参数位置做为参数别名。例如 #{param1},#{param2},这个是默认值。若是注解是 @Param("id"),那么参数就会被命名为 #{id}。spring
import com.nasus.mybatis.domain.Student;
import java.util.List;
public interface StudentService {
int add(Student student);
int update(String name, Integer age, Integer id);
int delete(Integer id);
Student findStudentById(Integer id);
List<Student> findStudentList();
}
复制代码
实现类:sql
import com.nasus.mybatis.dao.StudentMapper;
import com.nasus.mybatis.domain.Student;
import com.nasus.mybatis.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
/** * 添加 Student * @param name * @param age * @return */
@Override
public int add(Student student) {
return studentMapper.add(student);
}
/** * 更新 Student * @param name * @param age * @param id * @return */
@Override
public int update(String name, Integer age, Integer id) {
return studentMapper.update(name,age,id);
}
/** * 删除 Student * @param id * @return */
@Override
public int delete(Integer id) {
return studentMapper.delete(id);
}
/** * 根据 id 查询 Student * @param id * @return */
@Override
public Student findStudentById(Integer id) {
return studentMapper.findStudentById(id);
}
/** * 查询全部的 Student * @return */
@Override
public List<Student> findStudentList() {
return studentMapper.findStudentList();
}
}
复制代码
import com.nasus.mybatis.domain.Student;
import com.nasus.mybatis.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/Student")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("")
public int add(@RequestBody Student student){
return studentService.add(student);
}
@PutMapping("/{id}")
public int updateStudent(@PathVariable("id") Integer id, @RequestParam(value = "name", required = true) String name, @RequestParam(value = "age", required = true) Integer age){
return studentService.update(name,age,id);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable("id") Integer id){
studentService.delete(id);
}
@GetMapping("/{id}")
public Student findStudentById(@PathVariable("id") Integer id){
return studentService.findStudentById(id);
}
@GetMapping("/list")
public List<Student> findStudentList(){
return studentService.findStudentList();
}
}
复制代码
其余接口已经过 postman 测试,无问题。
源码下载:github 地址
以上为 SpringBoot 实战 (九) | 整合 Mybatis 的教程,除了注解方式实现之外,Mybatis 还提供了 XML 方式实现。想了解更多用法请移步官方文档。
最后,对 Python 、Java 感兴趣请长按二维码关注一波,我会努力带给大家价值,若是以为本文对你哪怕有一丁点帮助,请帮忙点好看,让更多人知道。
另外,关注以后在发送 1024 可领取免费学习资料。资料内容详情请看这篇旧文:Python、C++、Java、Linux、Go、前端、算法资料分享