Mybatis简化工厂

本文介绍了如何对Mybatis的工厂进行简化,从未简化的版本,通过分析代码并整合,实现了更简洁的SqlSessionFactory创建方式。测试结果显示,简化后的代码依然能成功插入数据,并能在数据库中查看到插入的数据。
摘要由CSDN通过智能技术生成

简化工厂

未简化版本

例:将数据使用插入语句插入到数据库中。

  1. 如下所示测试单元代码。
    @Test
    	public void test_insert() {
    
    		try {
    			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    			SqlSession sqlSession = sqlSessionFactory.openSession();
    
    			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    
    			Student s = new Student(1, "tom", "123@briup.com", new Date());
    			studentMapper.insertStudent(s);
    			sqlSession.commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
  2. 测试结果测试成功。
    在这里插入图片描述
  3. 分析
    代码使用io流将配置文件写入,再new了一个SqlSessionFactory工厂。
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				SqlSession sqlSession = sqlSessionFactory.openSession();

简化版

将如上所示三句,写成:

SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
@Test
	public void test_insert_util() {

		try {

			SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();

			StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
			Student s = new Student(2, "tom", "123@briup.com", new Date());
			studentMapper.insertStudent(s);
			sqlSession.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
  1. MyBatisSqlSessionFactory代码,直接调用即可。
package com.briup.utils;

import java.io.IOException;
import java.io.InputStream;

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 MyBatisSqlSessionFactory {
	private static SqlSessionFactory sqlSessionFactory;

	public static SqlSessionFactory getSqlSessionFactory() {
		if (sqlSessionFactory == null) {
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getCause());
			}
		}
		return sqlSessionFactory;
	}

	public static SqlSession openSession() {
		return openSession(false);
	}

	public static SqlSession openSession(boolean autoCommit) {
		return getSqlSessionFactory().openSession(autoCommit);
	}

}
  1. 测试结果成功。
    在这里插入图片描述

查看数据库

在这里插入图片描述
数据存在,插入成功。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值