Spring Boot 整合MyBatis
Spring Boot整合Mybatis
1. 创建一个Spring Boot工程
选择依赖:Lombok, Spring Web, Mybatis Framework, MySQL Driver
Lombok依赖只是为了使用实体时减少getter和setter的代码。
创建完后为项目添加必要的目录结构,最终结果如下:
生成的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.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybatis-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>mybatis-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 写代码
2.1 创建数据库
CREATE DATABASE IF NOT EXISTS `test`
USE `test`
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `tb_user` VALUES (1,'张三','123456');
INSERT INTO `tb_user` VALUES (2,'李四','666666');
2.1 创建如下代码结构
User.java
package com.example.demo.entity;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String password;
}
这里使用Lombok提供的@data
注解,省去了getter和setter的书写
UserDao.java
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserDao {
List<User> listAll();
}
UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import java.util.List;
public interface UserService {
List<User> getAll();
}
UserServiceImpl.java
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.repository.UserDao;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserDao userDao;
public List<User> getAll() {
return userDao.listAll();
}
}
需要注意的是,这里使用Lombok提供的注解@RequiredArgsConstructor
来生成一个构造方法用来注入UserDao的。
由于UserDao.java
中的@Mapper
注解是Mybatis提供的,Spring Boot不能识别为Spring中的一个Bean,这里如果直接使用@Autowired
的方式直接注入UserDao编译器会报错,但是不影响程序的运行,可以在UserDao
中加上Spring Boot的注解@Repository
,这就不会提示报错了。如下所示:
/**
* UserDao.java的另一种写法
*/
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserDao {
List<User> listAll();
}
/**
* UserServiceImpl.java的另一种写法
*/
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.repository.UserDao;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public List<User> getAll() {
return userDao.listAll();
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/getAll")
public List<User> getAll() {
return userService.getAll();
}
}
UserMapper.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.example.demo.repository.UserDao">
<resultMap id="User" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
</resultMap>
<select id="listAll" resultMap="User">
SELECT id, name, password
FROM tb_user
</select>
</mapper>
application.yml
server:
port: 8080
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.2.245:3306/test
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
3. 浏览器访问
http://localhost:8080/user/getAll
4. 补充
如果在stater中添加@MaperScan
注解则UserDao中的@Mapper
可以省略不写.
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value = "com.example.demo.repository")
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}