Spring boot整合Mybatis

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

1、Spring boot簡介

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

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

​ 因此,用最簡練的語言歸納就是:web

Spring 是一個「引擎」;spring

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

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

2、建立項目

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

img

圖 1-1

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

img

圖 1-2

三、繼續點擊"Next"按鈕,而後是"finsh",則工程即創建下來,pom.xml文件填寫以下所示:restful

<?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操做的可能。

3、項目開發

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

圖 2-1

二、啓動代碼以下所示:

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容器管理的)進行檢測。

三、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 "增長用戶";
    }
}

四、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(「包路徑」)註解。

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

五、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;

}

六、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);
    }
}

七、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>

八、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

4、項目運行

項目運行結果以下:

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

5、參考

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

相關文章
相關標籤/搜索