1. 程式人生 > >【Java】SpringMVC整合mybatis 連線池c3p0和druid分別實驗

【Java】SpringMVC整合mybatis 連線池c3p0和druid分別實驗

1.pom.xml

Spring框架包 mybatis包 AOP包 aspectj包 aopalliance包

<!-- mysql start -->
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <version>5.1.6</version>  
</dependency>  
<!-- mysql end -->
<!-- 連線池  支援oracle  mysql-->
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.5</version> </dependency> <!--或者--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId
>
<version>0.9.5-pre10</version> </dependency> <!-- 連線池 end --> <!--mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <dependency>
<groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency>
2.web.xml:
<!-- druid -->
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>
3.application.properties
jdbc.mysql.driverClass=com.mysql.jdbc.Driver
jdbc.mysql.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis
jdbc.mysql.user=xxxxx
jdbc.mysql.password=xxxxxx
jdbc.mysql.maxPoolSize=20
jdbc.mysql.maxIdleTIme=1000
jdbc.mysql.minPoolSize=6
jdbc.mysql.initalPoolSize=5
4.applicationContext.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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:cache="http://www.springframework.org/schema/cache" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	http://www.springframework.org/schema/cache
	http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
	
	<context:property-placeholder location="classpath:application.properties" />
	
	<context:annotation-config />
	<!-- 使用annotation 自動註冊bean,並保證@Required,@Autowired,@Resource的屬性被注入 -->
	<context:component-scan base-package="com.naton" />
	
	
	<import resource="spring-mysql.xml"/>
	<import resource="spring-aop.xml"/>

	<!-- 多檔案上傳 -->
	<!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> -->
	<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
</beans>
5.spring-aop.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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       ">
   
    <!-- spring aop -->
   <aop:aspectj-autoproxy />


</beans>
6.spring-mysql.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       
       http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd 
       
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       
       http://mybatis.org/schema/mybatis-spring  http://mybatis.org/schema/mybatis-spring.xsd">

    <!-- 開啟註解 -->
    <context:annotation-config />
    
    <!-- 一、使用資料庫連線池註冊資料來源,引入相關的配置檔案 暫時用c3p0 -->
    <import resource="c3p0.xml"/>
    
    <!-- 二、建立mybatis會話工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="cpdataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>  
    </bean> 
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="cpdataSource" />
    </bean>
	<tx:annotation-driven transaction-manager="transactionManager"/>
	 <!-- 三、建立mybatis會話template -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
       <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

    <!-- 註冊介面類的bean,使得程式中可以用註解方式獲取 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
     <property name="basePackage" value="com.naton.dao" />  
  </bean>  

</beans>
7.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>  
    <mappers>  
        <mapper resource="com/naton/dao/mapper/UserMapper.xml"/>  
    </mappers>  
</configuration>

8.c3p0.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 一、使用c3p0連線池註冊資料來源 -->
    <bean id="cpdataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <!-- 基礎配置 -->
       <property name="jdbcUrl" value="${jdbc.mysql.jdbcUrl}"></property>
     <property name="driverClass" value="${jdbc.mysql.driverClass}"></property>
     <property name="user" value="${jdbc.mysql.user}"></property>
     <property name="password" value="${jdbc.mysql.password}"></property>

     <!-- 關鍵配置 -->
     <!--初始化時獲取三個連線,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
     <property name="initialPoolSize" value="3"></property>
     <!--連線池中保留的最小連線數。Default: 2 -->
     <property name="minPoolSize" value="2"></property>
     <!--連線池中保留的最大連線數。Default: 15 -->
     <property name="maxPoolSize" value="15"></property>
     <!--當連線池中的連線耗盡的時候c3p0一次同時獲取的連線數。Default: 3 -->
     <property name="acquireIncrement" value="3"></property>

     <!-- 效能配置 -->
     <!-- 控制資料來源內載入的PreparedStatements數量。如果maxStatements與maxStatementsPerConnection均為0,則快取被關閉。Default: 0 -->
     <property name="maxStatements" value="8"></property>
     <!-- maxStatementsPerConnection定義了連線池內單個連線所擁有的最大快取statements數。Default: 0 -->
     <property name="maxStatementsPerConnection" value="5"></property>
     <!--最大空閒時間,1800秒內未使用則連線被丟棄。若為0則永不丟棄。Default: 0 -->
     <property name="maxIdleTime" value="1800"></property>
    </bean>

</beans>
9.實驗過程:
package com.naton.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.naton.dao.UserMapper;
import com.naton.pojo.po.User;
import com.naton.service.TxTestService;


@Controller
public class MybatisController {
    
    @Autowired
    TxTestService txTestService;
    
    @RequestMapping(value = "/mybatis/text")
    @ResponseBody
    public String text(HttpServletRequest request) {

        return "{\"what\":\"hi\"}";
    }
    
    
    @RequestMapping(value = "/mybatis/InsertTest")
    @ResponseBody
    public String test(HttpServletRequest request) {
 
        txTestService.insert();
        
        return "";
    }
}

package com.naton.service;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.naton.dao.UserMapper;
import com.naton.pojo.po.User;


@Transactional
@Service
public class TxTestService {

    @Autowired
    UserMapper userMapper;

    public void insert() {
        for (int i = 0; i < 100; i++) {
            User u = new User();
            u.setUsername(UUID.randomUUID().toString());
            u.setPassword(UUID.randomUUID().toString());
            userMapper.insert(u);
        }
        
        
        throw new RuntimeException();
    }
    
    
}

UserMapper.java、 User.java、UserMapper.xml都是通過之前介紹的工具生成好的http://blog.csdn.net/jack_eusong/article/details/78537125

//UserMapper.java
package com.naton.dao;

import org.springframework.stereotype.Service;

import com.naton.pojo.po.User;

@Service
public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

package com.naton.pojo.po;

//User.java
public class User {
	    private Integer id;

	    private String username;

	    private String password;

	    public Integer getId() {
	        return id;
	    }

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

	    public String getUsername() {
	        return username;
	    }

	    public void setUsername(String username) {
	        this.username = username == null ? null : username.trim();
	    }

	    public String getPassword() {
	        return password;
	    }

	    public void setPassword(String password) {
	        this.password = password == null ? null : password.trim();
	    }
}
//UserMapper.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="com.naton.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="com.naton.pojo.po.User" >
    <id column="ID" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    ID, username, password
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from tb_user
    where ID = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tb_user
    where ID = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.naton.pojo.po.User" >
    insert into tb_user (ID, username, password
      )
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.naton.pojo.po.User" >
    insert into tb_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.naton.pojo.po.User" >
    update tb_user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where ID = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.naton.pojo.po.User" >
    update tb_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where ID = #{id,jdbcType=INTEGER}
  </update>
</mapper>
  1. 啟動程式,訪問http://localhost:8080/mybatis/InsertTest,執行後,到資料庫中看了一下,確實插入了100條資料。整合完成。

11.實驗druid部分

druid.xml 注意druid 的id與之前c3p0中的id是一樣的,主要是為了快速切換,少改東西。

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 一、使用druid資料庫連線池註冊資料來源 -->
  <bean id="cpdataSource" class="com.alibaba.druid.pool.DruidDataSource">
     <!-- 基礎配置 -->
     <property name="url" value="${jdbc.mysql.jdbcUrl}"></property>
     <property name="driverClassName" value="${jdbc.mysql.driverClass}"></property>
     <property name="username" value="${jdbc.mysql.user}"></property>
     <property name="password" value="${jdbc.mysql.password}"></property>

     <!-- 關鍵配置 -->
     <!-- 初始化時建立物理連線的個數。初始化發生在顯示呼叫init方法,或者第一次getConnection時 --> 
     <property name="initialSize" value="3" /> 
     <!-- 最小連線池數量 --> 
     <property name="minIdle" value="2" /> 
     <!-- 最大連線池數量 --> 
     <property name="maxActive" value="15" />
     <!-- 配置獲取連線等待超時的時間 --> 
     <property name="maxWait" value="10000" />

     <!-- 效能配置 -->
     <!-- 開啟PSCache,並且指定每個連線上PSCache的大小 --> 
     <property name="poolPreparedStatements" value="true" /> 
     <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

     <!-- 其他配置 -->
     <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 --> 
     <property name="timeBetweenEvictionRunsMillis"