MyBatis學習-使用Druid鏈接池將Maybatis整合到spring

前言

MyBatis學習-鏈接oracle實現CURD操做實現了MyBatis基本配置與CRUD操做。可是每次都是手工建立SqlSessionFactory本篇將經過spring來管理bean,同時使用Druid鏈接池替換自帶的鏈接池。html

什麼是Druid鏈接池

Druid是一個JDBC組件,它包括三部分:java

  • DruidDriver 代理Driver,可以提供基於Filter-Chain模式的插件體系。
  • DruidDataSource 高效可管理的數據庫鏈接池。
  • SQLParser

Druid能夠作什麼?

  1. 能夠監控數據庫訪問性能,Druid內置提供了一個功能強大的StatFilter插件,可以詳細統計SQL的執行性能,這對於線上分析數據庫訪問性能有幫助。
  2. 替換DBCP和C3P0。Druid提供了一個高效、功能強大、可擴展性好的數據庫鏈接池。
  3. 數據庫密碼加密。直接把數據庫密碼寫在配置文件中,這是很差的行爲,容易致使安全問題。DruidDruiver和DruidDataSource都支持PasswordCallback。
  4. SQL執行日誌,Druid提供了不一樣的LogFilter,可以支持Common-Logging、Log4j和JdkLog,你能夠按須要選擇相應的LogFilter,監控你應用的數據庫訪問狀況。

擴展JDBC,若是你要對JDBC層有編程的需求,能夠經過Druid提供的Filter-Chain機制,很方便編寫JDBC層的擴展插件。mysql

導入庫包

鏈接oracle

若是咱們要鏈接oracle數據庫,須要導入oralce的jdbc的包。可是因爲oracle收費, 所以maven沒有oracle庫包,須要咱們本身手工導入外部包。或者也能夠將oracle的jar導入到maven庫中。具體導入步驟能夠查看Maven添加Oracle的依賴及驅動redis

<dependency>
  <groupId>com.oracle.jdbc</groupId>
  <artifactId>ojdbc6</artifactId>
  <version>11.2.0.1.0</version>
</dependency>

鏈接mysql

因爲mysql是免費的,咱們能夠經過maven直接安裝mysql的jdbc數據庫鏈接包spring

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

導入mybatis

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

導入druid

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.11</version>
</dependency>

導入spring-jdbc包

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

導入spring包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

導入spring事務相關包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>

導入mybatis-spring整合包

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

配置

下面使用過mysql數據庫爲例。sql

數據庫配置

在resources目錄下新建一個mysql.properities文件,用於配置鏈接數據庫的相關配置。數據庫

druid.url=jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC
#這個能夠缺省的,會根據url自動識別
druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.username=root
druid.password=123456

##初始鏈接數,默認0
druid.initialSize=10
#最大鏈接數,默認8
druid.maxActive=30
#最小閒置數
druid.minIdle=10
#獲取鏈接的最大等待時間,單位毫秒
druid.maxWait=2000
#緩存PreparedStatement,默認false
druid.poolPreparedStatements=true
#緩存PreparedStatement的最大數量,默認-1(不緩存)。大於0時會自動開啓緩存PreparedStatement,因此能夠省略上一句設置
druid.maxOpenPreparedStatements=20

druid配置

在resources目錄下新建一個applicationContext-mysql.xml文件,用於配置mysql的druid的數據庫鏈接池配置以及注入到spring的bean。編程

  1. 數據源的配置從mysql.propertie獲取的
<!--從mysql.properties加載配置-->
    <context:property-placeholder location="classpath:mysql.properties" />
    <!--druid鏈接池-->
  <bean name="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
      <property name="url" value="${druid.url}" />
      <property name="driverClassName" value="${druid.driverClassName}" />
      <property name="username" value="${druid.username}" />
      <property name="password" value="${druid.password}" />
      <property name="initialSize" value="${druid.initialSize}"/>
      <property name="maxActive" value="${druid.maxActive}" />
      <property name="minIdle" value="${druid.minIdle}" />
      <property name="maxWait" value="${druid.maxWait}" />
      <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
      <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}" />
  </bean>
  1. spring管理事務
<!--事務管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="druidDataSource"/>
</bean>
<!-- 使用annotation註解方式配置事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
  1. 根據mapper生成代理

sqlSessionFactory須要注入數據源和配置文件路徑,spring會生成runoob_tblMapper,咱們經過這個值取bean就能對數據庫進行操做了。緩存

<!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用來產生sqlSessionFactory的 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--注入數據源-->
    <property name="dataSource" ref="druidDataSource"/>
    <property name="configLocation" value="classpath:conf.xml"/>
</bean>

<!-- MapperFactoryBean:根據mapper接口生成的代理對象 -->

<bean id="runoob_tblMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="mysql.dao.runoob_tblMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

完整配置以下安全

<context:property-placeholder location="classpath:mysql.properties" />

  <!--druid鏈接池-->
<bean name="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="url" value="${druid.url}" />
    <property name="driverClassName" value="${druid.driverClassName}" />
    <property name="username" value="${druid.username}" />
    <property name="password" value="${druid.password}" />
    <property name="initialSize" value="${druid.initialSize}"/>
    <property name="maxActive" value="${druid.maxActive}" />
    <property name="minIdle" value="${druid.minIdle}" />
    <property name="maxWait" value="${druid.maxWait}" />
    <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
    <property name="maxOpenPreparedStatements" value="${druid.maxOpenPreparedStatements}" />
</bean>

<!--事務管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="druidDataSource"/>
</bean>
<!-- 使用annotation註解方式配置事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!--mybatis工廠-->

<!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用來產生sqlSessionFactory的 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--注入數據源-->
    <property name="dataSource" ref="druidDataSource"/>
    <property name="configLocation" value="classpath:conf.xml"/>
</bean>

<!-- MapperFactoryBean:根據mapper接口生成的代理對象 -->

<bean id="runoob_tblMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="mysql.dao.runoob_tblMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
  1. 添加conf.xml 配置映射的文件
<configuration>
    <mappers>
        <mapper resource="mapper/runoob_tblMapper.xml"></mapper>
    </mappers>
</configuration>
  1. 在resources/mapper下添加runoob_tblMapper.xml
<mapper namespace="mysql.dao.runoob_tblMapper">

   <insert id="insert" parameterType="mysql.dto.runoob_tbl" keyProperty="runoob_id" useGeneratedKeys="true">
    insert into runoob_tbl(runoob_title, runoob_author, submission_date) values(#{runoob_title},#{runoob_author},#{submission_date})
  </insert>
</mapper>

添加一個dto

在mysql.dto添加類

public class runoob_tbl {

    public  String runoob_id;
    public  String runoob_title;
    public  String runoob_author;
    public Date  submission_date;
    @Override
    public String toString() {
        return this.runoob_id + "," + this.runoob_title + "," + this.runoob_author + "," + this.submission_date;
    }

    public String getRunoob_id() {
        return runoob_id;
    }

    public void setRunoob_id(String runoob_id) {
        this.runoob_id = runoob_id;
    }

    public String getRunoob_title() {
        return runoob_title;
    }

    public void setRunoob_title(String runoob_title) {
        this.runoob_title = runoob_title;
    }

    public String getRunoob_author() {
        return runoob_author;
    }

    public void setRunoob_author(String runoob_author) {
        this.runoob_author = runoob_author;
    }

    public Date getSubmission_date() {
        return submission_date;
    }

    public void setSubmission_date(Date submission_date) {
        this.submission_date = submission_date;
    }
}

在數據庫中添加表

create table runoob_tbl
(
    runoob_id int unsigned auto_increment primary key,
    runoob_title    varchar(100) not null,
    runoob_author   varchar(40)  not null,
    submission_date date null
)charset = utf8;

建立mapper

在mysql.dao添加runoob_tblMapper.java

這個接口名須要和runoob_tblMapper配置的命名空間一致

public interface runoob_tblMapper {
    int insert(runoob_tbl tbl);
}

添加入庫的單元測試

須要在pom引入junit包

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

添加ruidmybatistest單元測試,插入一條記錄。

public class ruidmybatistest {

    @Test
    public void testGetUserList(){
        try
        {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-mysql.xml");
            runoob_tblMapper mapper = ctx.getBean("runoob_tblMapper",runoob_tblMapper.class);
            runoob_tbl tbl = new runoob_tbl();
            tbl.setRunoob_author("jake");
            tbl.setRunoob_title("redis");
            tbl.setSubmission_date(new Date());
            int count =  mapper.insert(tbl);
            System.out.println(count);
        }catch (Exception exception)
        {
            System.out.println(exception.getMessage());
        }
    }

}

經過MapperScannerConfigurer減小配置

經過上面配置,每一個mapper都須要配置bean,若mapper比較多,配置的就很麻煩,能夠經過MapperScannerConfigurer實現自動掃描,而無需配置mapper了
在sqlSessionFactory添加一個mapperLocations屬性,映射mapper下全部Mapper結尾的配置。

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--注入數據源-->
    <property name="dataSource" ref="druidDataSource"/>
    <property name="configLocation" value="classpath:mapperConf.xml"/>
    <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
</bean>
<!--    <bean id="runoob_tblMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!--        <property name="mapperInterface" value="mysql.dao.runoob_tblMapper"/>-->
<!--        <property name="sqlSessionFactory" ref="sqlSessionFactory" />-->
<!--    </bean>-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="mysql.dao" />
</bean>

新增一個student表

create table student
(
	name varchar(32) null,
	age int null,
	id int auto_increment,
	constraint student_pk
		primary key (id)
);

添加studentdto

public class student {

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

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

添加studentdao

public interface studentMapper {
    List<runoob_tbl>  selectByNames(List<String> name);
}

添加studentmapper.xml

在resources/mapper下添加studentmapper.xml

<mapper namespace="mysql.dao.studentMapper">

    <select id="selectByNames" resultType="mysql.dto.student">
          select * from student where name in
          <foreach item="name" index="index" collection="list" open="(" separator="," close=")">#{name}</foreach>
   </select>
</mapper>

添加單元測試

public class studenttest {

    @Test
    public void testGetList(){
        try
        {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-mysql.xml");
            studentMapper mapper = ctx.getBean("studentMapper",studentMapper.class);
            List<Integer> ages=  new ArrayList<Integer>();
            ages.add(10);
            ages.add(20);
            List<student> blog = mapper.selectByAge(ages);
            for (student item : blog) {
                System.out.println(item);
            }
        }catch (Exception exception)
        {
            System.out.println(exception.getMessage());
        }
    }

}

參考文獻

  1. Maven添加Oracle的依賴及驅動
相關文章
相關標籤/搜索