• MyBatis单列工厂的实现


    MyBatis单列工厂的实现

    SqlSessionFactoryUtils

    package com.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    /**
     * @author: XDZY
     * @date: 2018/8/8 14:50
     * @description: SessionFactory工厂
     */
    public class SqlSessionFactoryUtils {
        private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
    
        private static SqlSessionFactory sqlSessionFactory = null;
    
        private SqlSessionFactoryUtils() {
        }
    
        public static SqlSessionFactory getSqlSessionFactory() {
            synchronized (LOCK) {
                if (sqlSessionFactory != null) {
                    return sqlSessionFactory;
                }
                String resource = "com/mybatis-config.xml";
                InputStream inputStream;
                try {
                    inputStream = Resources.getResourceAsStream(resource);
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
                return sqlSessionFactory;
            }
        }
    
        public static SqlSession openSqlSession() {
            if (sqlSessionFactory == null) {
                getSqlSessionFactory();
            }
            return sqlSessionFactory.openSession();
        }
    }

    Test

    package com.main;
    
    import com.mapper.RoleMapper;
    import com.pojo.Role;
    import com.utils.SqlSessionFactoryUtils;
    import org.apache.ibatis.session.SqlSession;
    
    /**
     * @author: XDZY
     * @date: 2018/8/8 15:12
     * @description: 运行入口
     */
    public class TestMain {
        public static void main(String[] args) {
            SqlSession sqlSession = null;
            try {
                sqlSession = SqlSessionFactoryUtils.openSqlSession();
                RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
                Role role = roleMapper.getRole(1L);
                System.out.println(role.getRoleName());
            } finally {
                if (sqlSession != null) {
                    sqlSession.close();
                }
            }
        }
    }
  • 相关阅读:
    设计一个移动应用的本地缓存机制
    LeetCode 15
    POJ 2411
    Mahout构建图书推荐系统【一起学Mahout】
    firefox篇
    zTree实现删除树节点
    Tomcat与Servlet工作流程
    cocos2d 重写顶点着色语言
    将HTML格式的String转化为HTMLElement
    JQuery总结
  • 原文地址:https://www.cnblogs.com/xdzy/p/9638832.html
Copyright © 2020-2023  润新知