1. 程式人生 > 實用技巧 >Springboot 整合mybatis最完整教程

Springboot 整合mybatis最完整教程

前言:

各位同學大家好,最近在學習springboot整合mybatis的知識點,正好放假有時間寫了一個springboot整合mybatis的經典案例所以就分享大家,希望能幫助到同學對於springboot框架的學習,那麼廢話不多說我們正式開始

準備工作

1安裝好idea 或者eclispe +sts開發環境
2安裝maven 並配置環境
怎麼使用idea 這個工具一鍵建立springboot工程
這些在我之前的教程都講的很清楚 這裡我就不展開細說 有興趣的同學可以去看我以前的文章】
Springboot搭建零基礎教程:https://www.jianshu.com/p/c48595fdbf39

需要用到三方庫

  <!--java -web依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--資料庫依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

建表語句

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.7.17-log : Database - mybdtisdemo
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybdtisdemo` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */;

USE `mybdtisdemo`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `password` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `age` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `sex` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

/*Data for the table `user` */

insert  into `user`(`id`,`name`,`password`,`age`,`sex`) values (2,'xuqing','xq9527','27','男');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

application.ymal 的配置 如下圖:

server:
  port: 8090
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mybdtisdemo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  #配置Mapper.xml對映檔案
mybatis:
  mapper-locations: classpath*:mybatis/mapper/*.xml

準備按設定了utf-8編碼和 serverTimezone=UTC 和時區 以及資料庫賬號和密碼 jdbc 驅動 這些都配置好以後我們啟動一下

我們看到專案正常的啟動了我們開啟postman工具訪問一下 測試的介面

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userservice;
    @RequestMapping("/index")
    public  Object index(){
        return  "部署成功";
    }


我們看到有一個部署成功的字串返回 專案整個算是正常啟動成功我們需要加入一些業務邏輯程式碼來配合Sprigboot整合mybatis框架 來實現我們的業務需求

具體實現:

1建立bean類(資料模型)

package com.example.mybatis_demo.bean;
public class User {
    private int id;
    private String name;
    private String password;
    private String age;
    private String sex;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

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

    public String getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

bean類裡面的屬性我們最好要跟我們資料庫對應表中的欄位保持一致

2建立 Mapper類

package com.example.mybatis_demo.dao;
import com.example.mybatis_demo.bean.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserDao {
    @Select("select * from  user")
   public List<User>getallUser();

    @Select("select * from  user  where  id= #{id}")
    public User getuserbyId(Integer id);

    @Insert("insert into user (name,password, age ,sex) values (#{name},#{password},#{age},#{sex})")
    int addUser(User user);

    @Select("select * from  user  where  name= #{name}")
    public User getuserbyname(String name);

    @Update("update  user set password =#{password}  where  name= #{name}")
    public  int  upDatePassword(@Param("name") String name,
                                @Param("password") String password);
    @Delete("delete from user WHERE id = #{id}")
    int  deleteUser(@Param("id")Integer id);
}

我們需要用到的sql語句我們都在 Mapper類中用註解來實現 我們就不需要在Contorller中寫大量的sql語句了是不是使得程式碼可讀性和管理也方便

3建立service 層

package com.example.mybatis_demo.service;
import com.example.mybatis_demo.bean.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;

public interface UserService {
     List<User> getallUser();
    User getuserbyId(Integer id);
    int addUser(User user);
    User getuserbyname(String name);
    String  upDatePassword(String name, String password, String newpsw);
    int  deleteUser(Integer id);
}

service 層的介面類定義的一些方法(包括增刪改查的方法)是給controller 來呼叫的

4處理service 層 實現層 impl層

package com.example.mybatis_demo.service.impl;
import com.example.mybatis_demo.bean.User;
import com.example.mybatis_demo.dao.UserDao;
import com.example.mybatis_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service(value = "userService")
public class UserServiceimpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public List<User> getallUser() {
        return userDao.getallUser();
    }
    /**
     * @param id
     * @return
     * 通過頭id查詢資料
     *
     *
     */
    @Override
    public User getuserbyId(Integer id) {
        return userDao.getuserbyId(id);
    }

    /**
     * @param user
     * @return
     * 新增資料
     */
    @Override
    public int addUser(User user) {
        return userDao.addUser(user);
    }

    //通過使用者名稱查詢資料
    @Override
    public User getuserbyname(String name) {
        return null;
    }
    /**
     * @param name
     * @param password
     * @return
     * 更新資料
     *
     */
    @Override
    public String upDatePassword(String name, String password, String newpsw) {
          User user=userDao.getuserbyname(name);
          if(user!=null){
            if(user.getPassword().equals(password)){
                  userDao.upDatePassword(name,newpsw);
                  return "success";
              }else{
                  return "defeated";
              }
          }else{
              return  "fail";
          }
    }
    @Override
    public int deleteUser(Integer id) {
        return userDao.deleteUser(id);
    }

}

這一層是真正的sercvie業務邏輯的實現我們需要用Autowired 這個註解來引入剛才的 Mapper類來處理對資料庫裡面的資料操作(增刪改查)

通常大家在使用的時候

 @Autowired
  UserDao userDao;

都會有紅色報錯提示 這個不用管 這是IDE的問題我們的程式碼可以正常執行的

5 controller 層具體業務邏輯實現:

1新增資料:

  @RequestMapping("/adduser")
    public  Object addUser(
                           @RequestParam (value = "name")String name,
                           @RequestParam (value = "password")String password,
                           @RequestParam (value = "age")String age,
                           @RequestParam (value = "sex")String sex){
        Map<String,Object>map=new HashMap<>();
        User user=new User();
        user.setName(name);
        user.setPassword(password);
        user.setAge(age);
        user.setSex(sex);
        int addcode=userservice.addUser(user);
        if(addcode==1){
            map.put("code",200);
            map.put("msg","新增資料成功");
        }else {
            map.put("code",100);
            map.put("msg","新增資料失敗");
        }
        return map;
    }

我們開啟postman測試一下

介面給我們返回新增資料成功,我們開啟資料庫視覺化工具查詢下

我們看到資料庫裡面已經插入一條資料了

2查詢資料:

2.1查詢所有資料
    @RequestMapping("/getalluser")
    public  Object getAllUser(){
        List<User>data=userservice.getallUser();
        Map<String,Object>map=new HashMap<>();
        if(data!=null&&data.size()>0){
            map.put("code",200);
            map.put("msg","獲取資料成功");
            map.put("data",data);
        }else{
            map.put("code",100);
            map.put("msg","暫時沒有資料");
        }
        return  map;
    }

我們開啟postman測試請求一下

我們看到獲取到資料庫中所有的資料,因為只有一條所以json陣列中只有一條

2.2查詢單條資料

這個時候我們需要傳入資料庫中user表的頭id來進行查詢我們看程式碼實現

   @RequestMapping("/getusetbyid")
    public  Object getUserById(@RequestParam (value = "id") Integer id){
        User user=userservice.getuserbyId(id);
        Map<String,Object>map=new HashMap<>();
        if(user!=null){
            map.put("code",200);
            map.put("msg","獲取資料成功");
            map.put("user",user);
        }else{
            map.put("code",100);
            map.put("msg","暫時沒有資料");
        }
        return  map;
    }

我們來測試一下

我們可以看到通過介面我們把資料庫user表中 id=2的資料查詢到並且返回

3更新資料:

 @RequestMapping("/updatepassword")
    public  Object updatePassword(@RequestParam(value = "name") String  name,
                                  @RequestParam (value = "password")String password,
                               @RequestParam (value = "newpsw")String newpsw) {
        Map<String, Object> map = new HashMap<>();
        if (TextUtils.Isempty(name) || TextUtils.Isempty(password) || TextUtils.Isempty(newpsw)) {
            map.put("msg", "賬號或者密碼不能為空");
            map.put("code", 100);
            return map;
        } else {
            if (password.equals(newpsw)) {
                map.put("msg", "新密碼和舊密碼不能一樣");
                map.put("code", 101);
                return map;
            } else {
                String infindpsw = userservice.upDatePassword(name, password, newpsw);
                if (infindpsw.equals("success")) {
                    map.put("msg", "修改密碼成功");
                    map.put("code", 200);
                    return map;
                } else if (infindpsw.equals("defeated")) {
                    map.put("msg", "舊密碼不對");
                    map.put("code", 102);
                    return map;
                } else if (infindpsw.equals("fail")) {
                    map.put("msg", "不存在該使用者");
                    map.put("code", 103);
                    return map;
                } else {
                    map.put("msg", "伺服器錯誤");
                    map.put("code", 104);
                    return map;
                }
            }
        }
    }

更新password 這個欄位 我們需要前端傳入 name password newpsw 3個欄位來處理更新操作我們先空判,然後判斷新密碼箇舊密碼不一樣 ,然後我們呼叫service 層的更新資料的方法即可

更新前資料庫資料:


我們用postman測試一下更新資料的介面

我們再次查詢資料庫

更新後資料庫資料:


我們看到資料庫中的資料已經更新過來了

4刪除資料:

     @RequestMapping("/deleteuser")
    public  Object deleteUser(@RequestParam (value = "id")Integer id){
        Map<String,Object>map=new HashMap<>();
        User user=userservice.getuserbyId(id);
        if(user!=null){
            int deletecode=userservice.deleteUser(id);
            if(deletecode==1){
                map.put("code",200);
                map.put("msg","刪除資料成功");
            }else {
                map.put("code",100);
                map.put("msg","刪除資料失敗");
            }
        }else{
            map.put("code",101);
            map.put("msg","不存在該條資料");
        }
        return map;

    }

刪除資料我們需要傳入user表的頭id來處理刪除拿一條資料,這邊我們是先呼叫了查詢的方法先檢視資料庫中是否存在該條資料如果不存在直接返回不存在該條資料,如果存在我再呼叫刪除的方法刪除資料庫中對應id的資料

我們先查詢資料庫刪除前的資料


然後我們呼叫刪除資料的介面,我們開啟postman測試請求一下

我們看到返回刪除資料成功,我們再開啟資料查詢一下改條資料是否存在 (id=2的資料庫)

刪除後的資料:


我們可以看到資料庫中id=2的資料已經不存在,已經我們用介面請求刪除了 。
到此整個springboot整合mybatis 的教程就講完了

最後總結:

mybatis相對於過去 java web jsp和簡單的SpringDataJPA 框架算是一個折中的方案,既保留了sql語句的靈活性又使得程式碼可閱讀性更強,這裡的我使用的註解的方式來寫的sql語句,當然你也可以用mybatis 逆向工程xml的形勢來寫業務邏輯的sql語句 這裡篇幅有限我就不展開講了,我們後期會講到, 有興趣的同學可以底下留言, 最後希望我的文章能幫助到各位解決問題 ,以後我還會貢獻更多有用的程式碼分享給大家。各位同學如果覺得文章還不錯 ,麻煩給關注和star,小弟在這裡謝過啦 也可以加我個人QQ/微信(1693891473)

專案地址:

碼雲 :https://gitee.com/qiuyu123/mybatisdemo
github:https://github.com/xq19930522/mybatis_demo

QQ 交流群: