web項目通過listener直接載入Mybatis設定檔

來源:互聯網
上載者:User

標籤:web項目通過listener直接載入mybatis設定檔

首先,webxml中配置listener,並配置設定檔的路徑作為參數   

<!-- 初始化mybatis設定檔路徑 --><context-param><param-name>mybatisConfigLocation</param-name><param-value>com/config/configuration.xml</param-value></context-param><!-- 初始化SessionFactory監聽器 --><listener><listener-class>com.mybatis.listener.MybatisLoaderListener</listener-class></listener>

第二步:

   定義MybatisLoaderListener和MybatisLoader類,MybatisLoaderListener繼承自MybatisLoader並且實現介面ServletContextListener

   MybatisLoaderListener的代碼如下:

   

package com.mybatis.listener;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.apache.log4j.Logger;public class MybatisLoaderListener extends MybatisLoader implements ServletContextListener {            private static final Logger log = Logger.getLogger(MybatisLoaderListener.class);                 @Override          public void contextDestroyed(ServletContextEvent arg0) {                    }                @Override          public void contextInitialized(ServletContextEvent event) {          log.info("init mybatis configuration start ...");        initSqlSessionFatory(event.getServletContext());        log.info("init mybatis configuration success.");        }    }

 MybatisLoader代碼如下:

package com.mybatis.listener;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.Reader;import javax.servlet.ServletContext;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.apache.log4j.Logger;public class MybatisLoader {private static final Logger log = Logger.getLogger(MybatisLoader.class); public static final String MYBATIS_CONFIG_LOCATION = "mybatisConfigLocation";        //sql會話工廠      private static SqlSessionFactory sqlSessionFactory = null;         public static SqlSessionFactory getSqlSessionFactory(){         return sqlSessionFactory;         }         public void initSqlSessionFatory(ServletContext servletContext) {        String configurationXml=servletContext.getInitParameter(MYBATIS_CONFIG_LOCATION);        try {              if(sqlSessionFactory == null){                  //使用項目src路徑(如果設定檔放到src目錄下,使用以下代碼載入)                Reader reader = Resources.getResourceAsReader(configurationXml);              sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);                log.debug("init sqlSessionFactory success");                //使用絕對路徑(如果設定檔放到WEB-INF目錄下,使用以下代碼載入)                        //Reader reader = new FileReader(servletContext.getRealPath(configurationXml));                        //sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);             }                        } catch (IOException ioex) {                            throw new RuntimeException("Get resource error:"+configurationXml, ioex);                        }          }  }

第三步:在Dao中使用

SqlSessionFactory sqlSessionFactory=MybatisLoader.getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession();  List list = sqlSession.selectList("com.foo.bean.BlogMapper.queryAllBlogInfo");

特別說明:

如果設定檔放到WEB-INF目錄下,必須使用絕對路徑去擷取Reader,org.mybatis.io.Resources本身不不支援將設定檔放置到WEB-INF目錄下;

舉例

<!-- 初始化mybatis設定檔路徑 -->

<context-param><param-name>mybatisConfigLocation</param-name><param-value>/WEB-INF/configuration.xml</param-value></context-param>

在MybatisLoader的方法initSqlSessionFatory中使用

 Reader reader = new FileReader(servletContext.getRealPath(configurationXml));  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);


web項目通過listener直接載入Mybatis設定檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.