spring+mybatis获得SQL Connection

第一种mybatis

确保在web.xml中使用listener配置spring,否则无法使用ContextLoader.getCurrentWebApplicationContext()得到WebApplicationContext。

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 

在applicationContext.xml中配置数据库连接所需的bean

    <bean id="DatabaseSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="111111" />
        <property name="initialSize" value="2" />
        <property name="minIdle" value="2" />
        <property name="maxActive" value="20" />
        <property name="maxIdle" value="20" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.my.test" />
    </bean>

    <!--关键通过bean的名字得到SqlSessionFactory-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="DatabaseSource" />
        <property name="configLocation" value="classpath:sqlmap-config.xml" />
    </bean>

 

 

编写代码得到Connection

WebApplicationContext webApplicationContext =ContextLoader.getCurrentWebApplicationContext();
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory )webApplicationContext.getBean("SqlSessionFactory");
SqlSession sqlSession = sqlSessionFactory.openSession();
Connection conn = sqlSession.getConnection();

 或

BasicDataSource basicDataSource=(BasicDataSource)ContextLoader.getCurrentWebApplicationContext().getBean("DatabaseSource");
try {
  Connection connection=basicDataSource.getConnection();
}catch(SQLException e){
  
}

 

 

你可能感兴趣的:(spring,Connection,mybatis)