美文网首页
mybatis 02 别名与工具类

mybatis 02 别名与工具类

作者: 小小机器人 | 来源:发表于2016-10-14 20:34 被阅读13次
    基本数据类型别名
    mybatis别名 映射数据类型
    string String
    byte Byte
    long Long
    short Short
    int Integer
    integer Integer
    double Double
    float Float
    boolean Boolean
    date Date
    decimal BigDecimal
    自定义别名:

    在 “myBatis-config.xml” 中添加<typeAliases>标签


    Paste_Image.png

    那么在userMapper.xml中就可以使用这些别名了

    Paste_Image.png
    工具类
    public class MybatisSessionFactory {
    
    
        private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
        private static SqlSessionFactory sessionFactory;
        
    
        private static String CONFIG_FILE_LOCATION = "myBatis-config.xml";
    
        static {
            buildSessionFactory();
        }
        
        private MybatisSessionFactory() {
        }
        
        /**获取session*/
        public static SqlSession getSession() throws Exception {
            SqlSession session = (SqlSession) threadLocal.get();
    
            if (session == null ) {
                if (sessionFactory == null) {
                    buildSessionFactory();
                }
                session = (sessionFactory != null) ? sessionFactory.openSession()
                        : null;
                threadLocal.set(session);
            }
    
            return session;
        }
    
    
        /**构建session工厂*/
        private static void buildSessionFactory() {
            Reader reader =null;
            try {
              //到src目录下获取主配置文件
                reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
                sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            } catch (Exception e) {
                System.err.println("%%%% Error Creating SessionFactory %%%%");
                e.printStackTrace();
            }finally{
                if(reader!=null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
        /**关闭session*/
        public static void closeSession() throws Exception {
            SqlSession session = (SqlSession) threadLocal.get();
            threadLocal.set(null);
    
            if (session != null) {
                session.close();
            }
        }
    
    }
    
    /*
     * 该工具类是线程安全的:
     * threadLocal.set(session)相当于是
     * threadLocal.put(threadLocal.currentThead,session)
     * 
     * threadLocal.get()相当于是
     * threadLocal.get(threadLocal.currentThead)
     * */
    
    

    相关文章

      网友评论

          本文标题:mybatis 02 别名与工具类

          本文链接:https://www.haomeiwen.com/subject/knhnyttx.html