從零搭建SSM之——C3P0等連接池的使用以及整合Mybatis

上一篇寫了原始的JDBC操作數據庫,那麼這一篇我會一步一步地整合C3p0連接池並且使用Mybatis整合連接池。

整合C3P0連接池

再回顧一下上一篇關於JDBC操作數據庫的流程:

 * 第一步:加載Driver類,註冊數據庫驅動至DriverManager;
 * 第二步:通過DriverManager,使用url,用戶名和密碼獲取連接(Connection)* 第三步:通過Connection,使用sql語句得到Statement對象;
 * 第四步:執行語句,將結果返回resultSet;
 * 第五步:對結果resultSet進行處理;
 * 第六步:倒敘釋放資源resultSet-》preparedStatement-》connection。

數據庫連接池就像是線程池,管理着批量的連接對象,我們直接從連接池獲取連接就可以了。

1.第一步:環境準備
     <!--這是mysql的jar包的maven座標        -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    
    <!--  配置C3P0連接池      -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>

這裏導入了c3p0的jar包。

2.第二步:使用c3p0獲取連接操作數據庫

使用連接池和普通的JDBC差別並不大,只是獲取連接的來源改變了。

private static DataSource ds= new ComboPooledDataSource();
Connection  connection=ds.getConnection();

ComboPooledDataSource是c3p0對JAVA DataSource接口的實現,即ComboPooledDataSource是c3p0的連接池,我們現在是從連接池中獲取連接。
後續對數據庫的操作與原始JDBC相同(以查詢爲例):

public static List<StudentEntity> show(String sql)
    {
        List<StudentEntity> list=new ArrayList<StudentEntity>();
        Connection connection=C3P0Config.getConnection();
        ResultSet resultSet=null;
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            resultSet=preparedStatement.executeQuery();
            StudentEntity student=null;
            while(resultSet.next())
            {
                student=new StudentEntity();
                student.setId(resultSet.getLong("id"));
                student.setName(resultSet.getString("name"));
                student.setAge(resultSet.getInt("age"));
                list.add(student);
            }
            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

        }

        return list;
    }

注:c3p0連接池需要配置屬性,c3p0會掃描配置文件。

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 這是默認配置信息 -->
    <default-config>
        <!-- 連接四大參數配置 -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/october?characterEncoding=utf8&amp;useSSL=false</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!-- 池參數配置 -->
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>

<!--    &lt;!&ndash; 專門爲oracle提供的配置信息 &ndash;&gt;-->
<!--    <named-config name="oracle-config">-->
<!--        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>-->
<!--        <property name="driverClass">com.mysql.jdbc.Driver</property>-->
<!--        <property name="user">root</property>-->
<!--        <property name="password">123</property>-->
<!--        <property name="acquireIncrement">3</property>-->
<!--        <property name="initialPoolSize">10</property>-->
<!--        <property name="minPoolSize">2</property>-->
<!--        <property name="maxPoolSize">10</property>-->
<!--    </named-config>-->
</c3p0-config>

Mybatis整合C3p0、JDBC

OK,現在開始整合Mybatis。

1.第一步 環境準備

(1)導入mybatis的jar包

<!--配置Mybatis        -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

(2)編寫mapper接口

package ThirdStep.mapper;

import Entity.StudentEntity;

import java.util.List;

public interface StudentMapper {

    List<StudentEntity> selectAll();

    void update(StudentEntity student);
}

(3)編寫mapper.xml(用於生成mapper的實現類,完成實際的CRUD操作)
studentMapper.xml

<?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="ThirdStep.mapper.StudentMapper">
    <resultMap id="BaseResultMap" type="ThirdStep.StudentEntity">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="age" jdbcType="INTEGER" property="age" />
    </resultMap>
    <sql id="Base_Column_List">
    id,name,age
  </sql>
    <select id="selectAll"  resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from student
    </select>
    <update id="update" parameterType="ThirdStep.StudentEntity">
        update student
        <set>
            <if test="name != null">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

(4)編寫Mybatis的配置文件
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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
             <!-- 注意,dataSource的原始參數只有三個,是mybatis提供的三個屬性:UNPOOLED、POOLED、JNDI。
                       而POOLED是mybatis提供的連接池,如果使用其他的數據源(連接池)需要繼承UnpooledDataSourceFactory類。-->
            <dataSource type="ThirdStep.C3P0DataSource" >
                <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/october?characterEncoding=utf8&amp;useSSL=false"/>
                <property name="driverClass" value="com.mysql.jdbc.Driver"/>
                <property name="user" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

注意:dataSource的原始參數只有三個,是mybatis提供的三個屬性:UNPOOLED、POOLED、JNDI。而POOLED是mybatis提供的連接池,如果使用其他的數據源(連接池)需要繼承UnpooledDataSourceFactory類,然後將此類的全限定名填寫至mybatis的dataSource屬性type值處:

package ThirdStep;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

public class C3P0DataSource extends UnpooledDataSourceFactory {

    public C3P0DataSource() {
        this.dataSource=new ComboPooledDataSource();
    }
}
2.第二步 運行Mybatis的Sqlsession
package ThirdStep;

import Entity.StudentEntity;
import ThirdStep.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class Main3 {

    public static void main(String[] args)throws Exception {

        System.out.println("第一遍查詢:");
        show();
        System.out.println("更新值:");
        update();
        System.out.println("再次查詢");
        show();
    }


    public static void show()throws Exception
    {
        InputStream in=Resources.getResourceAsStream("Mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(in);
        SqlSession session=sqlSessionFactory.openSession();
        StudentMapper studentMapper=session.getMapper(StudentMapper.class);
        List<StudentEntity> list=studentMapper.selectAll();
        for (StudentEntity entity : list) {
            System.out.println(entity);
        }
        session.close();
        in.close();
    }

    public static void update()throws Exception
    {
        InputStream in=Resources.getResourceAsStream("Mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(in);
        SqlSession session=sqlSessionFactory.openSession();
        StudentMapper studentMapper=session.getMapper(StudentMapper.class);
        StudentEntity student=new StudentEntity();
        student.setId(1);
        student.setName("MybatisTestUpdate");
        student.setAge(18);
        studentMapper.update(student);
        session.commit();///更新、保存等寫操作需要commit,並且會對緩存產生影響
        session.close();
        in.close();
    }
}

結果:
在這裏插入圖片描述

3.Mybatis的運行原理

Mybatis的核心是SqlSession

(1)Mybatis掃描配置文件中的mapper接口以及mapper.xml後會封裝JDBC以及SQL語句等等成爲一個mapper的實現類:
底層通過JDBC查詢得到Resultset,之後通過mapper.xml的resultmap封裝成對應類的對象返回。
(2)之後可以從Sqlsession處獲得實現類。完成數據庫的增刪改查操作。

大致爲:
在這裏插入圖片描述

OK,到這裏就結束了,後續我將整合Spring、Mybatis。Spring是一個IOC容器,用於管理Bean,具有控制反轉和依賴注入的功能。所以Spring整合Mybatis後,許多對象都直接從Spring容器中獲取,十分方便。

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