MyBatis工厂工具类 MyBatisUtils

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis工厂工具类 MyBatisUtils相关的知识,希望对你有一定的参考价值。

 

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

 

public class MyBatisUtils {

        

         private static SqlSessionFactory factory;

        

         static{

                   try{

                            factory =

                                     new SqlSessionFactoryBuilder()

                                               .build(

                                                                 Resources.getResourceAsStream("mybatis-cfg.xml")

                                                                 );

                   }catch(Exception e){

                            e.printStackTrace();

                            // 静态初始化代码块异常错误

                            throw new ExceptionInInitializerError(e);

                   }

         }

        

         /**

          * @Description 工具方法,创建会话对象使用.

          * @return 创建的会话对象.

          */

         public static SqlSession openSession(){

                   return factory.openSession();

         }

 

}

以上是关于MyBatis工厂工具类 MyBatisUtils的主要内容,如果未能解决你的问题,请参考以下文章

SSM-MyBatis-10:Mybatis中SqlSession的getMapper()和简单的工具类MyBatisUtils

MybatisUtils工具类

MyBatis

工具类MyBatisUtils创建SqlSessionFactory

Mybatis之执行自定义SQL举例

Mybatis-XML-入门示例