Spring boot整合Mybatis


​ 抽空寫個小demo,順便溫習下知識,自從用了Spring boot之后,怎一個爽字了得,開發起來太舒服了,目前Springboot已經成為了開發界的主流框架了,在此就將Spring與Mybatis的整合小例子寫下。

一、Spring boot簡介

​ 由於Spring框架本身需要大量的配置,各種繁重的配置,導致了低效率的開發、復雜的部署流程以及第三方技術集成難度大,在這種情況下Springboot應運而生,Springboot引入了自動配置的概念,使得項目設置變得非常簡便。同時Springboot本身並不是Spring框架的和新特性以及功能擴展,只是用於快速、敏捷地開發新一代基於Spring框架的應用程序。它並不是用來替代Spring的解決方案,而是和Spring框架緊密結合用於提升Spring開發者體驗的工具。

​ Springboot集成了大量常用的第三方庫配置(例如Jackson, JDBC, Mongo, Redis, Mail等等),Spring Boot應用中這些第三方庫幾乎可以零配置的開箱即用(out-of-the-box),大部分的Spring Boot應用都只需要很少的配置代碼,令開發者能夠更加專注於業務邏輯。

​ 所以,用最簡練的語言概括就是:

Spring 是一個“引擎”;

Spring MVC 是基於Spring的一個 MVC 框架;

Spring Boot 是基於Spring4的條件注冊的一套快速開發整合包。

二、創建項目##

1、 打開IDEA,File -> New  -> project 打開如下圖1-1所示的對話框

img

圖 1-1

2、點擊"Next"按鈕,如下圖1-2所示:

img

圖 1-2

3、繼續點擊"Next"按鈕,然后是"finsh",則工程即建立下來,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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>SpringbootAndMybatis</groupId>
    <artifactId>SpringbootAndMybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </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>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

pom.xml中幾個包的含義如下:

  1. spring-boot-starter-parent : 可以通過繼承spring-boot-starter-parent包來獲得一些合理的默認配置,在dependencies里的部分配置可以不用填寫version信息,自動繼承parent包的版本,也可以不使用該包。

  2. spring-boot-starter-web:用戶構建Web,包含restful風格框架SpringMVC和默認的嵌入式容器Tomcat,即該包整合了Spring mvc,同時自帶嵌入式tomcat,因此啟動項目時只要運行main方法就行,無需再配置Tomcat。

  3. mybatis-spring-boot-starter:該包為spring boot和mybatis的整合包。

  4. spring-boot-maven-plugin : 該插件能夠以Maven的方式為應用提供Spring Boot的支持,即為Spring Boot應用提供了執行Maven操作的可能。

三、項目開發#

1、項目結構如下圖2-1所示:

圖 2-1

2、啟動代碼如下所示:

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

在啟動類中只有一個注解@SpringBootApplication,該注解是組合注解,主要包括:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三個注解。

  • @SpringBootConfiguration:該注解繼承自@Configuration,一般與@Bean配合使用,使用這兩個注解就可以創建一個簡單的spring配置類,可以用來替代相應的xml配置文件。同時說明這是一個springboot項目的配置。

  • @EnableAutoConfiguration:該注解的意思就是Springboot可以根據你添加的jar包來配置你項目的默認配置,比如當你添加了mvc的jar包,它就會自動配置web項目所需的配置。springboot的自動配置功能就是由於該注解。

  • @ComponentScan:顧名思義該注解是用來掃描組件的,只要組件上有@component及其子注解@Service、@Repository、@Controller等,springboot會自動掃描到並納入Spring 容器進行管理,有點類似xml文件中的<context:component-scan>該注解不填屬性的話就是默認掃描啟動類所在的包,或者啟動類所在包的下一級,所以啟動類要放在最外層。

    在基於SpringBoot的應用中,通常需要將包含main方法的啟動類(即在main方法中通過執行SpringApplication.run方法來啟動應用)放在項目的根目錄,即與所有包平級。原因主要是啟動類自身是一個基於注解的配置類,使用@SpringBootApplication注解,其包括的@ComponentScan注解、@EnableAutoConfiguration注解都是掃描使用了這個注解的類所在的包及其子包,故放在項目根目錄,則可以掃描項目所有的包,對所有的類(具體為使用Spring容器管理的)進行檢測。

3、Controller類代碼如下所示:

package com.test.controller;

import com.test.dto.User;
import com.test.service.UserService;
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 UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private User user;
    //顯示用戶
    @RequestMapping("getUser")
    public List<User> getUser() throws Exception {
        return userService.getUser();
    }
    //刪除用戶
    @RequestMapping("delete/{id}")
    public String deleteUser(@PathVariable int id) throws Exception {
        userService.deleteUser(id);
        return "你已經刪掉了id為"+id+"的用戶";
    }
    //增加用戶
    @RequestMapping("addUser")
    public String addUser() throws Exception {
        user.setAge("18");
        user.setName("阿花");
        userService.addUser(user);
        return "增加用戶";
    }
}

4、dao層UserMapper代碼如下所示:

package com.test.dao;

import com.test.dto.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface UserMapper {

    //獲取用戶名單
    public List<User> getUser() throws Exception;
    //根據id刪除用戶
    public void deleteUser(int id)throws Exception;
    //新增用戶
    public void addUser(User user)throws Exception;

}

將mapper裝配到spring容器中去,要在mapper接口中加上@Mapper注解,或者在啟動類中加上@MapperScan(“包路徑”)注解。

5、dto中User實體類代碼如下:

package com.test.dto;

import org.springframework.stereotype.Component;

@Component
public class User {

    private int id;

    private String name;

    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 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;
    }
}

5、service層UserService接口代碼如下:

package com.test.service;

import com.test.dto.User;

import java.util.List;

public interface  UserService {

    //顯示所有用戶
    public List<User> getUser() throws Exception;
    //根據id刪除用戶
    public void deleteUser(int id) throws Exception;
    //新增用戶
    public void addUser(User user) throws Exception;

}

6、service層實現類UserServiceImpl代碼如下:

package com.test.impl;

import com.test.dao.UserMapper;
import com.test.dto.User;
import com.test.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 UserMapper userMapper;


    @Override
    public List<User> getUser() throws Exception {
        return userMapper.getUser();
    }

    @Override
    public void deleteUser(int id) throws Exception {
        userMapper.deleteUser(id);
    }

    @Override
    public void addUser(User user) throws Exception {
        userMapper.addUser(user);
    }
}

7、mapper配置文件user.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.dao.UserMapper">
    <select id="getUser" resultType="com.test.dto.User">
        select * from user
    </select>
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id =#{id}
    </delete>
    <insert id="addUser" parameterType="com.test.dto.User">
        insert into user(id,name,age,sex)values(#{id},#{name},#{age},#{sex})
    </insert>
</mapper>

8、application.properties配置文件內容如下:

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations: classpath:mapper/*.xml

四、項目運行#

項目運行結果如下:

到此,一個簡單的springboot整合Mybatis的一個小demo就完成了。

五、參考#

1、https://www.cnblogs.com/scuury/p/9501734.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM