【整合篇】SpringBoot整合MyBatis

版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://sunkuan.blog.csdn.net/article/details/107356186

文章目录

  • 一、准备工作
    • 1、准备数据表
    • 2、引入依赖(pom.xml)
    • 3、配置文件(application.yml)
    • 4、实体类
  • 二、持久层(repository)
    • 1、接口
    • 2、Mapper
  • 三、控制器(Controller)
  • 四、启动类
  • 五、Postman 演示效果






MyBatis 是一款主流的半自动化的 ORM(Object Relationship mapping,对象关系映射) 框架,它是 Apache 提供的开源项目,它以前叫做 iBatis,可以帮助开发者实现数据持久化工作。其实说的简单一些,它就是对 JDBC 进行了封装,使用它来操作数据库更加的方便。

还记得疫情期间我在家整理过一篇关于 《SSM 框架整合》 的博客,当时写了两天才搞定,虽然用了 Maven 来管理 jar 包,但过多的配置让我头疼。好了闲话不多说,本篇来给大家讲解使用 Spring Boot 来整合 MyBatis,看了本篇博客,你会觉得这辈子都不想配置 SSM 框架那些烦人的东东了。


一、准备工作

1、准备数据表

CREATE TABLE `t_student`  (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(40)
);

INSERT INTO `t_student` VALUES (1, '张三');
INSERT INTO `t_student` VALUES (2, '李四');
INSERT INTO `t_student` VALUES (3, '王五');

2、引入依赖(pom.xml)

<dependencies>
	
	<dependency>
		<groupId>mysqlgroupId>
		<artifactId>mysql-connector-javaartifactId>
		<scope>runtimescope>
	dependency>
	
	
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.1.3version>
    dependency>
	
	
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-webartifactId>
	dependency>
dependencies>

3、配置文件(application.yml)

server:
  port: 8888

spring:
  datasource:  # 配置数据源信息
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///demo?useUnicode=true&characterEncoding=UTF-8&nullCatalogMeansCurrent=true
    username: root
    password: 123456
 
mybatis:
  mapper-locations: classpath:/mapping/*.xml
  type-aliases-package: com.demo.entity

4、实体类

public class Student {
	private Long id;
	private String name;
    // get()... & set()...
}


二、持久层(repository)

1、接口

public interface StudentRepository {
	public Student findById(Long id);
}

2、Mapper



<mapper namespace="com.demo.repository.StudentRepository">
	<select id="findById" parameterType="java.lang.Long" resultType="Student">
		select * from t_student where id = #{id}
	select>
mapper>


三、控制器(Controller)

因为本篇只做整合讲解,所以为了方便我这里不使用三层架构来实现,直接通过控制器来调用持久层。

@RestController
public class StudentController {

	@Autowired
	private StudentRepository studentRepository;
	
	@GetMapping("/findById/{id}")
	public Student findById(@PathVariable("id") Long id) {
		return studentRepository.findById(id);
	}
	
}


四、启动类

记得在启动类上加 @MapperScan 注解哦~

@SpringBootApplication
@MapperScan("com.demo.repository")
public class MybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(MybatisApplication.class, args);
	}

}


五、Postman 演示效果

【整合篇】SpringBoot整合MyBatis_第1张图片

【整合篇】SpringBoot整合MyBatis_第2张图片



博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!



你可能感兴趣的:(SpringBoot,MyBatis)