前言:
网上关于这部分的资料有很多,但是都很零散,今天为了总结一下以前自己学习的,所以准备在这里写一篇完整的教程,希望对你们有用。

项目结构

[Mybatis+SpringBoot] 使用全注解方式实现SpringBoot整合Mybatis_xml

开发环境

  • 开工工具:IDEA
  • 基础工具:Maven JDK8
  • 技术:Spring+Mybatis
  • 数据库:Mysql
  • SpringBoot版本:2.1.1

创建工程


  • 创建springboot工程

[Mybatis+SpringBoot] 使用全注解方式实现SpringBoot整合Mybatis_mybatis_02

  • 工程这里就不细说了,贴一下pom文件内容吧。

<?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.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.asong.demo</groupId>
<artifactId>demomybat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demomybat</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>

创建数据库表

因为为了测试,我们的用户表只创建4个字段如下:

CREATE TABLE `user` (
`id` int(13) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(33) DEFAULT NULL COMMENT '姓名',
`age` int(3) DEFAULT NULL COMMENT '年龄',
`money` double DEFAULT NULL COMMENT '账户余额',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

配置application.yml文件

如下:

server:
port: 8080

spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimeznotallow=Asia/Shanghai
username: root
password:

这里需要注意的是,我们使用的mysql-connector-java 8+ ,JDBC 连接到mysql-connector-java 6+以上的需要指定时区 serverTimeznotallow=GMT%2B8。另外我们之前使用配置 Mysql数据连接是一般是这样指定driver-class-name=com.mysql.jdbc.Driver,但是现在不可以必须为 否则控制台下面的异常:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.

代码实现

1. 创建用户类Bean

public class User {
private int id;
private String name;
private int age;
private double money;

public User(){}

public User(int id, String name, int age, double money) {
this.id = id;
this.name = name;
this.age = age;
this.money = money;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public double getMoney() {
return money;
}

public void setId(int id) {
this.id = id;
}

public void setName(String name) {
this.name = name;
}

public void setAge(int age) {
this.age = age;
}

public void setMoney(double money) {
this.money = money;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", mnotallow=" + money +
'}';
}
}

2.Dao层

@Mapper
public interface UserDao {
/**
* 通过名字查询用户信息
*/
@Select("SELECT * FROM user WHERE name = #{name}")
User findUserByName(@Param("name") String name);

/**
* 查询所有用户信息
* @return
*/
@Select("SELECT * FROM user")
List<User> findAllUser();

/**
* 插入用户信息
* @param name
* @param age
* @param money
*/
@Insert("INSERT INTO user(name, age,money) VALUES(#{name}, #{age}, #{money})")
void insertUser(@Param("name") String name,@Param("age") Integer age,@Param("money") Double money);

/**
* 根据 id 更新用户信息
*/
@Update("UPDATE user SET name = #{name},age = #{age},mnotallow= #{money} WHERE id = #{id}")
void updateUser(@Param("name") String name, @Param("age") Integer age, @Param("money") Double money,
@Param("id") int id);

/**
* 根据 id 删除用户信息
*/
@Delete("DELETE from user WHERE id = #{id}")
void deleteUser(@Param("id") int id);
}

3. Service层

@Service
public class UserService {
@Autowired
private UserDao userDao;

/**
* 根据名字查找用户
* @param name
* @return
*/

public User selectUserByName(String name)
{
return userDao.findUserByName(name);
}

/**
* 插入两个用户
*/
public void insertService(){
userDao.insertUser("sunsong",22,4000.0);
userDao.insertUser("zhang",20,4000.0);
}

/**
* 查找所有用户
* @return
*/
public List<User> selectAllUser(){
return userDao.findAllUser();
}

/**
* 根据id删除用户
* @param id
*/
public void deleteService(int id)
{
userDao.deleteUser(id);
}
@Transactional
public void changemoney(){
userDao.updateUser("sunsong",21,2000.0,3);
//模拟转账过程中可能遇到的意外情况
int test = 1 / 0;
userDao.updateUser("zhang",19,3000.0,4);
}
}

4. Controller层

@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private UserService userService;

@RequestMapping("/query")
public User testQuery() {
return userService.selectUserByName("sunsong");
}

@RequestMapping("/insert")
public List<User> testInsert() {
userService.insertService();
return userService.selectAllUser();
}


@RequestMapping("/changemoney")
public List<User> testchangemoney() {
userService.changemoney();
return userService.selectAllUser();
}

@RequestMapping("/delete")
public String testDelete() {
userService.deleteService(3);
return "OK";
}
}

运行程序

[Mybatis+SpringBoot] 使用全注解方式实现SpringBoot整合Mybatis_mybatis_03


[Mybatis+SpringBoot] 使用全注解方式实现SpringBoot整合Mybatis_mybatis_04

总结

这个项目完全是通过全注解方式进行开发,还可以通过XML方式的进行开发,等我发下一次整理发出来吧,总体实现还是很简单。