首頁 > 軟體

詳解Spring與MyBatis的整合的方法

2022-03-18 13:02:05

一、問題提出

mybatis是根據mapper.xml檔案動態生成mapper介面的實現類,按照Spring的常規元件掃描的方式不能新增到IOC容器中,需要做出相應的設定

二、解決方案

圖片摘自尚矽谷尚籌網專案檔案。

如圖可知,需要在Spring和mybatis整合的組態檔中設定

  • 啟動Spring元件掃描
  • 資料來源
  • SqlsessionFactoryBean
  • MapperScannerConfigurer

三、MyBatis逆向工程

pom檔案

 
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
    </dependencies>
    <!-- 控制maven在構建過程中的設定 -->
    <build>
        <!--構建過程中用到的外掛-->
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.4.1</version>
                <!--外掛用的依賴-->
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.4.1</version>
                    </dependency>
                    <dependency>
                        <groupId>com.mchange</groupId>
                        <artifactId>c3p0</artifactId>
                        <version>0.9.5.5</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.25</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--mybatis generator:generate -->
    <context id="wdhTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!--是否去除自動生成的註釋 true:是 ;false:否 -->
            <property name="suppressAllComments" value="ture" />
        </commentGenerator>
        <!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
        <jdbcConnection
                driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/mbook"
                userId="root"
                password="123456">
        </jdbcConnection>
        <!--
        預設 false,把 JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把
        JDBC DECIMAL
        和 NUMERIC 型別解析為 java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--targetProject:生成 Entity類的路徑 -->
        <javaModelGenerator targetProject=".srcmainjava"
                            targetPackage="com.wdh.entity">
            <!--enableSubPackages:是否讓 schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
            <!--從資料庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--targetProject:XxxMapper.xml對映檔案生成的路徑 -->
        <sqlMapGenerator targetProject=".srcmainjava"
                         targetPackage="com.wdh.mapper">
            <!--enableSubPackages:是否讓 schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!--targetPackage Mapper介面生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetProject=".srcmainjava"
                             targetPackage="com.wdh.mapper">
            <!--enableSubPackages:是否讓 schema作為包的字尾 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 資料庫表名字和我們的 entity類對應的對映指定 -->
        <table tableName="login" domainObjectName="Login" />
    </context>
</generatorConfiguration>

生成結果:

 把生成的檔案移動到對應的工程檔案中

四、Spring與mybatis的組態檔

主模組依賴jar包

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.3.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.16</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>

spring-persist-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">    <!--啟動元件掃描-->    <context:component-scan base-package="com.wdh"/>    <!--參照jdbc.properties檔案-->    <context:property-placeholder location="classpath:jdbc.properties"/>    <!--設定druid資料來源-->    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">        <property name="username" value="${jdbc.username}"/>        <property name="password" value="${jdbc.password}"/>        <property name="url" value="${jdbc.url}"/>        <!--注意這裡是dirverClassName-->        <property name="driverClassName" value="${jdbc.driver}"/>    </bean>    <!--設定SqlSessionFactoryBean-->    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">        <!--設定資料來源-->        <property name="dataSource" ref="dataSource"/>        <!--設定mybatis-config檔案位置-->        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>        <!--設定mapper對映檔案位置-->        <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>    </bean>    <!--設定MapperScannerConfigurer-->    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <!--設定要掃描的包-->        <property name="basePackage" value="com.wdh.mapper"/>    </bean></beans><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--啟動元件掃描-->
    <context:component-scan base-package="com.wdh"/>
    <!--參照jdbc.properties檔案-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--設定druid資料來源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <!--注意這裡是dirverClassName-->
        <property name="driverClassName" value="${jdbc.driver}"/>
    </bean>
    <!--設定SqlSessionFactoryBean-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--設定資料來源-->
        <property name="dataSource" ref="dataSource"/>
        <!--設定mybatis-config檔案位置-->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
        <!--設定mapper對映檔案位置-->
        <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>
    </bean>
    <!--設定MapperScannerConfigurer-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--設定要掃描的包-->
        <property name="basePackage" value="com.wdh.mapper"/>
    </bean>
</beans>

 檔案目錄

五、測試

//junit與Spring整合
@RunWith(SpringJUnit4ClassRunner.class)
//載入Spring組態檔
@ContextConfiguration(locations = {"classpath:spring-persist-mybatis.xml"})
public class DataSourceTest {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private LoginMapper loginMapper;
    @Test
    public void connTest() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
    @Test
    public void insertTest(){
        Login login = new Login(2, "wdh", "123", false);
        int i = loginMapper.insert(login);
        System.out.println("受影響的行數:"+ i);
    }
}

 結果:

六、總結

 

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容! 


IT145.com E-mail:sddin#qq.com