spring+mybatis获得SQL Connection

阅读更多

第一种mybatis

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


  contextConfigLocation
  classpath:applicationContext.xml


    org.springframework.web.context.ContextLoaderListener

 

在applicationContext.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){
  
}

 

 

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