zoukankan      html  css  js  c++  java
  • mybatis入门

    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);
    	}
    

      

  • 相关阅读:
    The Worm Turns
    Equations
    Snail’s trouble
    WuKong
    Codeforces 369 C Valera and Elections
    POJ 2186 Popular Cows
    Codefroces 366 D Dima and Trap Graph (最短路)
    Codefroces 366 C Dima and Salad(dp)
    Codefroces 374 B Inna and Sequence (树状数组 || 线段树)
    Codeforces 374 C Inna and Dima (DFS)
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/6926273.html
Copyright © 2011-2022 走看看