spring:spring與mybatis的整合

努力生活的人發表於2020-10-19

spring與mybatis的整合

整合學習

整合的官方網站:參考文件

前提(版本需求):

MyBatis-SpringMyBatisSpring 框架Spring BatchJava
2.03.5+5.0+4.0+Java 8+
1.33.4+3.2.2+2.1+Java 6+

備註

要和 Spring 一起使用 MyBatis,需要在 Spring 應用上下文中定義至少兩樣東西:一個 SqlSessionFactory 和至少一個資料對映器類。

在 MyBatis-Spring 中,可使用SqlSessionFactoryBean來建立 SqlSessionFactory。要配置這個工廠 bean,只需要把下面程式碼放在 Spring 的 XML 配置檔案中:

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

作用:可以使用它來執行對映了的語句,提交或回滾連線

SqlSessionFactory(建立SqlSession(用來運算元據庫))有一個唯一的必要屬性:用於 JDBC 的 DataSource。這可以是任意的 DataSource 物件,它的配置方法和其它 Spring 資料庫連線是一樣的。

重點

SqlSessionTemplate 是 MyBatis-Spring 的核心。作為 SqlSession 的一個實現,這意味著可以使用它無縫代替你程式碼中已經在使用的 SqlSession(用來運算元據庫)

整合所需要依賴包(使用 Maven 作為構建工具)

1、相關jar包

junit

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
</dependency>

mybatis

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>

mysql-connector-java

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

spring相關

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.10.RELEASE</version>
</dependency>

aspectJ AOP 織入器

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

mybatis-spring整合包 【重點】

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.2</version>
</dependency>

配置Maven靜態資源過濾問題!

<build>
   <resources>
       <resource>
           <directory>src/main/java</directory>
           <includes>
               <include>**/*.properties</include>
               <include>**/*.xml</include>
           </includes>
           <filtering>true</filtering>
       </resource>
   </resources>
</build>

整合方式一

配置檔案

spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置資料來源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--    配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
<!--        關聯mybatis的配置檔案-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--    關聯mybatis-->
        <property name="mapperLocations" value="classpath:com/minjiang/dao/*.xml"></property>
    </bean>
<!--    關聯sqlSessionFactory-->
    <bean id = "sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--       利用構造器注入-->
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>
<!--    實現bean-->
    <bean id="userDao" class="com.minjiang.dao.impl.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"></property>
    </bean>
</beans>

mybatis(可以捨棄,但建議保留,可以用來做一些別名的設定,讓程式更有條理性)

<?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>

</configuration>

配置實體類

public class User {
    int id;
    String name;
    String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

配置dao層

介面

public interface UserMapper {
    public List<User> seletAll();
}

介面mapper檔案

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.minjiang.dao.UserMapper">
    <select id="seletAll" resultType="com.minjiang.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

介面實現類

@SuppressWarnings("all")
public class UserDaoImpl implements UserMapper {
    //sqlSession不用自己建立,spring來管理
    private SqlSessionTemplate sqlSession;
    //ioc
    public void setSqlSession(SqlSessionTemplate sqlSession){
        this.sqlSession = sqlSession;
    }

    public List<User> seletAll() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.seletAll();
    }
}

整合方式二

dao繼承Support類 , 直接利用 getSqlSession() 獲得 , 然後直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且對事務的支援更加友好 . 可跟蹤原始碼檢視

SqlSessionDaoSupport

一個抽象的支援類,提供SqlSession,呼叫getSqlSession()方法你會得到一個getSqlSession(),用於執行sql語句

實體類

public class User {
    int id;
    String name;
    String pwd;

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

dao層

介面

public interface UserMapper {
    public List<User> selectAll();
}

介面實現類

public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {

    public List<User> selectAll() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectAll();
    }
}

配置檔案

spring檔案

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--    整合步驟:
            1、配置資料來源
            2、配置SqlSessionFactory(同時關聯關聯mybatis)
            4、配置sqlSession(使用SqlSessionTemplate)
            5,實現bean(私有化SqlSession)
            -->
    <context:annotation-config/>
<!--    引入外部檔案-->
    <context:property-placeholder location="classpath:db.properties" />
<!--    配置資料來源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--    配置SqlSessionFactory
        擴充套件:,SqlSessionTemplate是SqlSession的實現類,如其名,是sqlSession模板
              SqlSessionFactory也是一個介面,是SqlSession工廠,他的能力就是開啟一個SqlSession會話
              SqlSessionFactoryBean是生產SqlSessionFactory的工廠bean。 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        需要搭載一個資料來源,原因:建立的SqlSession(用來運算元據庫的)-->
        <property name="dataSource" ref="dataSource"></property>
<!--        關聯mybatis的配置檔案-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--        關聯mybatis的bean檔案(使用註解開發可以捨棄)-->
        <property name="mapperLocations" value="classpath:com/minjiang/dao/*.xml"></property>
    </bean>
<!--    配置SqlSession(使用SqlSessionTemplate)-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sessionFactory"></constructor-arg>
    </bean>
<!--    私有化-->
    <bean id="userDao" class="com.minjiang.dao.impl.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sessionFactory" />
    </bean>
</beans>

mybatis檔案

<?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>

</configuration>

測試類

public class test02 {
    @Test
    public void test02(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper mapper = context.getBean("userDao", UserMapper.class);
        List<User> users = mapper.selectAll();
        for (User user : users){
            System.out.println(user);
        }
    }
}

相關文章