1、导入jar包
2、导入配置文件
3、编写测试类
//mybatis快速入门 @Test public void test00() throws IOException{ InputStream in = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(in); SqlSession ss=ssf.openSession(); String string = ss.toString(); System.out.println(string); }
4、为方便而写的单例模式的测试类
package com.wh.mapperImpl; /** * 将mybatis中事务管理这一块,用单例模式实现 */ 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 BaseDao { private static SqlSessionFactory ssf; public SqlSession ss; static { String resource = "mybatis.xml"; try { // 读取配置文件 InputStream in = Resources.getResourceAsStream(resource); // 创建连接工厂 ssf = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } // 获得连接 public SqlSession openSession() { if (ss == null) { // 事务自动提交,默认是false不自动提交 true自动提交 ss = ssf.openSession(true); } return ss; } // 提交 public void commit() { if (ss != null) { ss.commit(); } } // 回滚 public void rollback() { if (ss != null) { ss.rollback(); } } // 关闭连接 public void close() { if (ss != null) { ss.close(); } } }
//mybatis快速入门 @Test public void test() throws IOException{ //获得连接 SqlSession ss=BaseDao.openSession(); String string = ss.toString(); System.out.println(string); }