SpringBoot整合Mybatis(XML方式以及注解方式)


前言

本文将介绍SpringBoot如何整合MyBatis以及如何使用MyBatis进行开发
前提:1.已经搭建好SpringBoot环境(如果还没有搭建好,请先参照着我的上篇博客进行搭建SpringBoot环境搭建
2.已经添加MyBatis相关的依赖到工程中

项目目录结构如下:
在这里插入图片描述


一、MyBatis是什么?

MyBatis是一款优秀的持久层框架,它避免了所有的JDBC编码和手动设置参数以及获取结果集,让我们的开发更有效率。

二、整合步骤

1.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.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>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.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </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>
    </build>

</project>

create table test(
    id int primary key ,
    msg varchar(30)
);

2.编写实体类

实体类的代码如下:

package com.example.demo.pojo;

public class Message {
    
    
    private int id;
    private String msg;

    public int getId() {
    
    
        return id;
    }

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

    public String getMsg() {
    
    
        return msg;
    }

    public void setMsg(String msg) {
    
    
        this.msg = msg;
    }
}

3.编写Dao层

dao层的代码如下:
其中selectMessage()方法为遍历所有的记录,selectMessageById为根据id查询对应的记录

package com.example.demo.dao;


import com.example.demo.pojo.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository("messageDao")
@Mapper
public interface MessageDao {
    
    
    public List<Message> selectMessage();
    public Message selectMessageById(Message message);

 
}

4.编写SQL映射文件

注意:id要与接口方法的名称一致

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.dao.MessageDao">
    <select id="selectMessage" resultType="com.example.demo.pojo.Message">
        select id,msg from test;
    </select>

    <select id="selectMessageById" parameterType="com.example.demo.pojo.Message"
            resultType="com.example.demo.pojo.Message">
        select id,msg from test where id=#{id};
    </select>

</mapper>

写完之后别忘了在application.properties文件中声明mapper的位置

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=数据库地址
spring.datasource.username=数据库账号
spring.datasource.password=密码
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

mybatis.mapper-locations=classpath:mapper/*.xml

5.编写Service层

Service层的代码如下:

package com.example.demo.service;

import com.example.demo.dao.MessageDao;
import com.example.demo.pojo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;


@Service("messageService")
public class MessageService {
    
    
    @Autowired
    MessageDao messageDao;

    public List<Message> selectMessage(){
    
    
        return messageDao.selectMessage();
    }

    public Message selectMessageById(Message message){
    
    
        return messageDao.selectMessageById(message);
    }

   
}

6.编写Controller层

Controller层的代码如下:
@RestController相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面

package com.example.demo.controller;


import com.example.demo.pojo.Message;
import com.example.demo.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class TestController {
    
    
    @Autowired
    MessageService messageService;
    @RequestMapping("/test")
    public String testMapging(){
    
    
        return "hello SpringBoot";
    }

    @RequestMapping("/selectTest")
    public List<Message> testSelect(){
    
    
        return messageService.selectMessage();
    }

    @RequestMapping("/selectTestById/{id}")
    public Message test(@PathVariable int id){
    
    
        Message message = new Message();
        message.setId(id);
        return messageService.selectMessageById(message);
    }

   
    }
}


7.测试

测试selectMessage
在这里插入图片描述
测试selectMessageById
在这里插入图片描述
如果觉得XML编写太麻烦的话,也可以使用注解,接下来简单演示注解的使用:
在dao层增加一个接口方法select,并使用@Select注解

package com.example.demo.dao;


import com.example.demo.pojo.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository("messageDao")
@Mapper
public interface MessageDao {
    
    
    public List<Message> selectMessage();
    public Message selectMessageById(Message message);

    @Select("select * from test")
    public List<Message> selectMsg();
}

Service层代码如下:

package com.example.demo.service;

import com.example.demo.dao.MessageDao;
import com.example.demo.pojo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;


@Service("messageService")
public class MessageService {
    
    
    @Autowired
    MessageDao messageDao;

    public List<Message> selectMessage(){
    
    
        return messageDao.selectMessage();
    }

    public Message selectMessageById(Message message){
    
    
        return messageDao.selectMessageById(message);
    }

    public List<Message> selectMsg(){
    
    
        return messageDao.selectMsg();
    }
}

Controller层增加方法

   @RequestMapping("/selectMsgTest")
    public List<Message> selectMsg(){
    
    
        return messageService.selectMsg();
    }

至此就完成了,接下来测试一下
在这里插入图片描述


总结

以上就是如何SpringBoot整合MyBatis框架,对比SSM,会发现SpringBoot少了很多配置文件的编写,让我们更加的专注于业务逻辑上,而不是编写繁琐的配置。

猜你喜欢

转载自blog.csdn.net/weixin_44116132/article/details/108824168