Spring整合Mybatis的一般步驟(IDEA版)

易嗔先生發表於2020-10-07

Spring整合Mybatis的一般步驟(IDEA版)

  • 方式一

    1. 先在專案的pop.xml檔案下新增相關依賴(spring-wewbmvc、aspectjrt、aspectjweaver、junit、mysql-connector-java、mybatis、spring-jdbc、mybatis-spring)
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.4</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
    </dependencies>

注:若對應介面的xml檔案未放置在resources資料夾下,還需要新增以下內容,使啟動時可以訪問其他目錄下的xml檔案。

 <build>
        <resources>
            <resource>
                <directory>
                    src/main/resources
                </directory>
                <includes>
                    <include>
                        **/*.properties
                    </include>
                    <include>
                        **/*.xml
                    </include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
  1. 在專案的resources包下,建立spring-dao.xml檔案(建立spring提供的datasource來獲取資料庫的資料來源、通過資料來源獲取sqlsessionfactory、再通過sqlsessionfactory獲取到sqlsessionTemplate、註冊對應的介面等)和mybatis.xml(設定日誌、起別名、指定介面對應的xml問價位置等)
  • spring-dao.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>

        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--<property name="mapperLocations" value="classpath:com/whut/Mapper/*.xml"/>-->
    </bean>

    <bean id="sqlsession" class="org.mybatis.spring.SqlSessionTemplate">

        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.whut.Mapper.UserMapperImpl">
        <property name="sqlsession" ref="sqlsession"/>
    </bean>
</beans>
  • mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.whut.pojo"/>
    </typeAliases>

    <mappers>
        <mapper resource="com/whut/Mapper/UserMapper.xml"/>
    </mappers>
</configuration>
  1. 在Mapper(介面包)下編寫對應的xml檔案(需要在mybatis-config.xml中指定資源位置)和介面的實現類
    -UserMapper介面
public interface UserMapper {
    List<User> select();
}
	-UserMapper的實現類
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlsession;//在spring_dao.xml中通過SqlSessionFactory獲取
    public void setSqlsession(SqlSessionTemplate sqlsession) {
        this.sqlsession = sqlsession;
    }

    public List<User> select() {
        UserMapper userMapper = sqlsession.getMapper(UserMapper.class);
        return userMapper.select();
    }
}
	-UserMapper對應的xml檔案
<mapper namespace="com.whut.Mapper.UserMapper">
        <select id="select" resultType="com.whut.pojo.User">
            select * from user;
        </select>
</mapper>
  1. 編寫測試類進行測試
 @Test
    public void testselect(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring_dao.xml");
        UserMapper userMapper = context.getBean("userMapper",UserMapper.class);
        List<User> userList = userMapper.select();
        for (User user : userList) {
            System.out.println(user);
        }
    }
  • 方式二
    是對方式一的簡化,方式一在獲取sqlsession時需要先在實現類中定義私有變數sqlsession,然後設定set方法,再通過spring-dap.xml中注入來獲取到sqlsession。
    方式二直接在建立實現類時通過繼承SqlsessionDaoSupport來獲取到sqlsession方法(getsession()),然後再spring-dao.xml中注入,直接通過sqlsessionfactory來得到sqlsession物件!

    • 方式二下的介面實現類寫法
  public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
      public List<User> select() {
          return getSqlSession().getMapper(UserMapper.class).select();
      }
  }

相關文章