【Maven配置四】配置Spring+整合MyBatis實現動態掃描開發

Spring框架是一個開放源代碼的J2EE應用程序框架,它使得我們的開發過程更簡單,可以大大減少工作量,提高效率。spring具有輕量化、ioc(控制反轉)、aop(面向切面編程)思想、mvc模式等特性,在企業中被廣泛使用。

今天我們使用Maven完成spring的配置以及和MyBatis的整合。


動態掃描過程圖

ApplicationContext
DataSource連接池
SqlSessionFactory
MapperScannerConfiurer動態掃描器
Mapper接口
Mapper配置
後續操作...

配置xml

配置pom.xml

pom.xml中加入properties,指定spring版本:

<properties>
  <spring.version>5.0.2.RELEASE</spring.version>
</properties>

<dependencies>中引入spring的全部包、mybatis以及mybatis-spring整合包、c3p0連接池、mysql數據庫驅動、

<dependency>   
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency> 
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${spring.version}</version>
</dependency>

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

<dependency>
  <groupId>mysql</groupId> 
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.17</version>
</dependency>
<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>

配置ApplicationContext.xml

resources目錄中創建ApplicationContext.xml,引入以下內容:

mybatis-spring.jar提供了很多方便的類:

  • SqlSessionFactoryBean可以直接配置SqlSessionFactory而不需要我們提供mybatis-config.xml配置文件。
    需要參數dataSource: 提供一個連接池
  • MapperScannerConfigurer會自動掃描mapper包內的所有mapper映射文件,使得我們直接一步直接獲得mapper接口
    它會自動讀取ApplicationContext.xml中配置的SqlSessionFactoryBean工廠類,並自動生成所有的mapper接口
    需要參數basePackage: 指定mapper包的位置
<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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

  <!-- 配置c3p0連接池 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
    <property name="jdbcUrl"
              value="jdbc:mysql://localhost:3306/hello_mysql?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
    <property name="user" value="root"/>
    <property name="password" value="123"/>
  </bean>

  <!-- 配置SqlSessionFactory -->
  <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
  </bean>

  <!-- 配置MapperScannerConfigur動態掃描 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="mapper"/>
  </bean>
</beans>

通過mybatis-spring的整合,我們就不需要再配置mybatis-config.xml了。


提供bean和mapper

要實現動態掃描開發,我們需要提供一個bean實現類,並且提供mapper接口和對應的mapper.xml配置文件。

筆者這裏直接使用MyBatis Generator生成了bean(pojo)實現類和mapper配置文件以及mapper接口:

pojo/Users中生成的實現類:

package pojo;

public class Users {
  private Integer id;
  String name;
  private Integer age;

  public Users(Integer id, String name, Integer age) {
    this.id = id;
    this.name = name;
    this.age = age;
  }

  public Users() {
    super();
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name == null ? null : name.trim();
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return id + ", " + name + ", " + age;
  }
}

mapper/UsersMapper中生成的接口文件,MyBatis Generator爲我們自動生成了各種方法:

package mapper;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import pojo.Users;
import pojo.UsersExample;

public interface UsersMapper {
    long countByExample(UsersExample example);
    int deleteByExample(UsersExample example);
    int deleteByPrimaryKey(Integer id);
    int insert(Users record);
    int insertSelective(Users record);
    List<Users> selectByExample(UsersExample example);
    Users selectByPrimaryKey(Integer id);
    int updateByExampleSelective(@Param("record") Users record, @Param("example") UsersExample example);
    int updateByExample(@Param("record") Users record, @Param("example") UsersExample example);
    int updateByPrimaryKeySelective(Users record);
    int updateByPrimaryKey(Users record);
}

實現訪問數據庫

基於mybatis-spring下的動態掃描開發,要訪問數據庫非常簡單,筆者此處實現了一個UsersTest類,使用junit進行測試,只需3行代碼我們就可以訪問數據庫並返回數據了:

package test;

import mapper.UsersMapper;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Users;

public class UsersTest {
  @Test
  public void test1() {
    //讀取spring配置文件
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    //得到mapper映射接口
    UsersMapper mapper = applicationContext.getBean(UsersMapper.class);
    //執行mapper中的操作
    Users user = mapper.selectByPrimaryKey(1);
    //輸出結果
    System.out.println(user);
  }
}

測試成功,控制檯中正確返回了結果(此處DEBUG數據來自log4j):

DEBUG [main] - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@410ae9a3 [wrapping: com.mysql.cj.jdbc.ConnectionImpl@319988b0]] will not be managed by Spring
DEBUG [main] - ==>  Preparing: select id, name, age from users where id = ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7d3430a7]
DEBUG [main] - Returning JDBC Connection to DataSource
1, Adam, 13

完整目錄(此處service包可忽略):
在這裏插入圖片描述

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