【springboot spring mybatis】看我怎麼將springboot與spring整合mybatis與druid數據源

概述

本文分別講述了springspringboot是怎麼整合mybatisdruid數據源的?如果你只是想實現其中一種,那你就不要把他們的配置過程搞混了。
mybatis

1、mybatis

MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名爲MyBatis 。2013年11月遷移到Github
MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java對象)映射成數據庫中的記錄。

在國內以及韓國等地mybatis的普及率還是很高的。所以mybatis是絕對值得學習的。

2、druid

Druid提供了一個高效、功能強大、可擴展性好的數據庫連接池,druid還有自己的數據訪問監聽系統,你的系統數據調用實時狀況你都一通過druid來查看。

壹:spring整合

在整合mybatis之前,我們首先需要明確的是,我們需要哪些文件分別拿來幹嘛的。

  • 1、pom.xml
    – maven用於引入依賴的
  • 2、jdbc.properties
    – 配置mybatis的數據源
  • 3、mybatis-config.xml
    – 配置mybatis參數

一:文件結構

我們可以看淡我的整個的項目結構就是這樣的,這裏使用的是maven管理項目,直接建立maven項目即可,不懂maven的安裝與配置的可以見我另一篇博文maven的安裝與配置,配置好後,直接在新建項目裏選擇maven即可。
:我的mybatis-config.xml直接就是放在spring-config.xml,歸根到地,他們都是spring的配置文件,只是命名不同而已。
目錄結構

二:配置文件

1、pom.xml

pom.xml文件,有了這個文件之後,我們不需要像以前一樣去找jar包,找到還不一定兼容,maven項目裏,你直接在你的pom.xml文件裏寫相關依賴,他就會自動導入,jar包也會自動下載好,下面就是我們整合mybatis所需要的的相關依賴。

<!--        數據庫  start-->
        <!--        引入jdbc與mysql依賴-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.8</version>
        </dependency>
        <!--引入druid數據源-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <!--        mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- spring整合mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
<!--        數據庫 end-->

2、jdbc.properties

這個文件主要用於存放我們mybatis連接的數據庫參數,依次爲驅動、url、用戶名、密碼參數,你只需要換成你自己的就好了,設置好之後,我們需要下一個配置文件來加載。

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/world?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=qwer1234

3、mybatis-config.xml

這時,你會疑問,咦,上面的文件結構圖中沒有這個文件啊?
我的mybatis-config.xml直接就是放在spring-config.xml,歸根到地,他們都是spring的配置文件,只是命名不同而已。當然,也可以單獨配置一個,只需要在啓動的時候加載他就可以了。

整合druid數據源,就在這個文件裏配置即可。


  <!-- 這個是加載下面的mapper與service注入到容器中,這樣你才能使用,注意你自己的包名-->
    <context:annotation-config/>
    <context:component-scan base-package="com.lomtom"/>
    
    <!-- 配置 讀取properties文件 jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties" />
<!--        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
<!--            <property name="location" value="classpath:jdbc.properties"/>-->
<!--        </bean>-->

    <!-- 配置 數據源 整合druid-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

<!--    spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/lomtom/mapper/*.java"/>
    </bean>


    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lomtom.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

二:java代碼

1、mapper

mybatis裏,支持兩種寫法,一種是註解版,一種是xml版,這裏推薦使用註解版。
mybatis我使用的是註解版,註解版簡單。如果使用xml版,需要配置maven的靜態資源訪問。

package com.lomtom.mapper;

import com.lomtom.model.User;
import org.apache.ibatis.annotations.*;

/**
 * User: lomtom
 * Date: 2020/3/2
 * Time: 16:45
 */
@Mapper
public interface UserInfoMapper {
    @Select("select * from user where username = #{username} and password = #{password}")
    User login(@Param("username") String username,@Param("password") String password);
}

2、service

一般來說,我們爲了規範,還是建一個service層。這裏是實現service接口,你還需要自己寫UserInfoService接口,加上login();函數即可,不是很難,就不板述了。

package com.lomtom.service;

import com.lomtom.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * User: lomtom
 * Date: 2020/3/2
 * Time: 17:21
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public boolean login(String username, String password) {
        return userInfoMapper.login(username, password) != null;
    }
}

3、測試

我使用的是spring測試單元測試的,需要在pom.xml引入JUNIT依賴,當然,你也可以直接寫一個main函數調用。

最後的結果就不展示了,他無非就是一句登陸成功,或者登陸失敗。

import com.lomtom.model.HelloWorld;
import com.lomtom.service.UserInfoService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * User: lomtom
 * Date: 2020/3/2
 * Time: 19:45
 */

//測試類
public class test {

    private ApplicationContext context;
    @Before
    public void setUp() throws Exception {
//        加載配置文件
        context = new ClassPathXmlApplicationContext("spring-config.xml");
    }

    @Test
    public void Test2(){
        UserInfoService userInfoService =  context.getBean(UserInfoService.class);
        boolean flag = userInfoService.login("admin","123456");
        if (flag){
            System.out.println("登錄成功。。。。");
        }
        else{
            System.out.println("登陸失敗。。。");
        }
    }
}

參考:
spring與mybatis四種整合方法

貳:springboot整合

相對於springspringboot的整合就簡單的多,因爲在springboot裏,很多都是自動配置的,相當於就是對spring的再一次封裝,所以在springboot裏,很多東西就變得簡單很多。
相比spring,我們不需要配置麻煩的spring配置xml文件,只需要在application.yml文件中配置即可。當然,pom.xml時maven所需要的,所以他也是必不可少的。
建立項目的時候,選擇spring initializr就可以快速建立一個springboot項目,當然如果你想自己配置,那我也是無法阻攔的。

1、pom.xml

springboot與spring引入mybatis所需依賴,是不同的,所以你最好還是複製這裏的,這裏我也是吸取了教訓的。哈哈哈

 <!--        引入jdbc與mysql依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--引入druid數據源-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        
        <!--日誌打印-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

2、application.yml(resources下)

與spring不同的是,在springboot裏,不需要建很多的配置文件,你所有的配置參數全部卸載這裏面即可。
在springboot裏面,配置文件有兩種,一種是properties,另一種是yml,兩種語法有點不同,不過都可以作爲springboot的配置文件,

spring:
	datasource:
	    username: root
	    password: qwer1234
	    url: jdbc:mysql://localhost:3306/world?serverTimezone=UTC&characterEncoding=utf-8
	    #    不寫driver-class-name則自動分配
	    #    driver-class-name: com.mysql.cj.jdbc.Driver
	    #    配置druid數據源
	    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  #註解版與xml版不能共同使用
  ##  指定全局配置的路徑(xml版配置)
  #  config-location: classpath::mybatis/mybatis-config.xml
  ##  指定sql映射文件的位置(xml版配置)
  #  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    #    開啓駝峯命名法
    map-underscore-to-camel-case: true
logging:
  #  開啓com.lomtom.blog.mapper包下所有的日誌(在調用時)
  level:
    com.lomtom.myblog1.mapper: debug

3、druid配置

雖然說在springboot裏面配置數據源,但是如果我們想要通過網頁端訪問的話,需要配置以下內容,我們就可以通過訪問druid的來查看web的數據狀態。
訪問地址:http://localhost:8080/druid,然後輸入賬號密碼就可以訪問。

package com.lomtom.myblog1.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * User: lomtom
 * Date: 2020/1/4
 * Time: 21:09
 */

@Configuration
public class DruidConfig {


    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    //設置druid監控
    //1、設置管理後臺的servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams=new HashMap<>();
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","admin");
        initParams.put("allow","");
//        initParams.put("deny","");

        registrationBean.setInitParameters(initParams);
        return  registrationBean;
    }
    //2、設置web的監控filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new WebStatFilter());
        Map<String,String> initParams=new HashMap<>();
        initParams.put("exclusion","*.js,*.css,/druid/*");

        registrationBean.setInitParameters(initParams);
        //添加過濾規則
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        return  registrationBean;
    }
}

訪問http://localhost:端口名/druid
druid

4、mapper

在spring裏面,還要配置文件進行包掃面,而在springboot裏面直接加@Mapper註解即可,springboot會自動註冊的。然後直接調用即可。

import com.lomtom.myblog1.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * User: lomtom
 * Date: 2020/1/30
 * Time: 17:49
 */

/**
 * 用戶的mapper類
 */
@Mapper
public interface UserMapper {

    @Select("select * from user where userName=#{username} or email=#{username}")
    User getUserByUsername(String username);
}

5、測試

在spring boot裏,在啓動的時候不需要手動配置加載文件,所有的一切,他都會自動配置完成,你只管調用就可以了。

當然,最後的結果就不展示了,他無非就是一句登陸成功,或者登陸失敗。

package com.lomtom.myblog1;

import com.lomtom.myblog1.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Myblog1ApplicationTests {


    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
        boolean flag = userMapper.login("admin","123456");
        if (flag){
            System.out.println("登錄成功。。。。");
        }
        else{
            System.out.println("登陸失敗。。。");
        }
    }
}

作者有話

本文主要介紹了springspringboot分別怎麼整合mybatis的,相信你看了之後,如果你還是初學者,那麼問題是免不了的,但是誰不是這麼過來的呢,你唯一能做的就是發現問題-找到問題-解決問題,當然,如果你在配置過程中有問題,筆者還是很樂意爲你解答的。

而談及spring與spring boot,spring boot就是spring的拓展,他主要消除了spring複雜繁多的xml配置文件,實現極大程度的自動化配置,所以看到我們在整合mybatis時,配置變得相當簡單,當然,最爲筆者的建議,你要是會spring boot,一定要明白他其中的自動配置原理,然後再去回顧spring時,你就會驚訝的發現,哦~,原來他是這樣的。很多東西就會豁然開朗。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章