mybatis使用工具类生成sqlSession

注:由于sqlSession的创建代价很大,所以我们要把sqlSession变成单例的。

1、mapper.xml




	
		INSERT INTO STUDENT(NAME, AGE, SCORE) VALUES(#{name}, #{age}, #{score})
	

2、mybatis.xml




	
	
		
			
			
				
				
				
				
			
		
	
	
	
	
		
	

3、StudentDaoImpl

package com.dao;

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

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 com.beans.Student;
import com.utils.SqlSessionUtils;

public class StudentDaoImpl implements IStudentDao {

	private SqlSession sqlSession;
	
	@Override
	public void insertStudent(Student student) {
		
		try {
			SqlSession sqlSession = SqlSessionUtils.getSqlSession();
			
			sqlSession.insert("insertStudent", student);
			
			sqlSession.commit();
		} 
		finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

}

4、SqlSessionUtils

package com.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 SqlSessionUtils {
	
	private static SqlSession sqlSession;

	public static SqlSession getSqlSession() {
		
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			sqlSession = sqlSessionFactory.openSession();
			return sqlSession;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}

5、MyTest

package com.test;



import org.junit.Test;

import com.beans.Student;
import com.dao.IStudentDao;
import com.dao.StudentDaoImpl;

public class MyTest {
	
	private IStudentDao dao;
	
	@org.junit.Before
	public void Before() {
		dao = new StudentDaoImpl();
	}
	
	@Test
	public void testInsert() {
		Student student = new Student("王五", 25, 95.5);
		dao.insertStudent(student);
	}

}

6、log4j.propeties

log4j.appender.console = org.apache.log4j.ConsoleAppender  

log4j.appender.console.Target = System.out  

log4j.appender.console.layout = org.apache.log4j.PatternLayout  

log4j.appender.console.layout.ConversionPattern = [%-5p] %m%n  

log4j.logger.test = debug,console

你可能感兴趣的:(mybatis使用工具类生成sqlSession)