ibatis又名(mybatis)使用方法,针对jdbc的封装

1.先导入包到项目lib文件夹中;

2.在src根目录文件中建立:SqlMapConfig.xml




	
		
		
	
	
		
			
			
				
				
				
				
			
		 
	
	
		
		
	


3.编写映射文件:

Admin.xml文件




	
		insert into t_admin (username,password) values (#{username},#{password})
	
	
	

4.利用ibatisAPI文档直接拿来使用:
 
  

 
  

package cn.com.leadfar.cms.backend.dao.impl;

import org.apache.ibatis.session.SqlSession;

import cn.com.leadfar.cms.backend.dao.AdminDao;
import cn.com.leadfar.cms.backend.model.Admin;
import cn.com.leadfar.cms.utils.MyBatisUtil;

public class AdminDaoForMyBatisImpl extends BaseDao implements AdminDao {

	public void addAdmin(Admin admin) {
		add(admin);
	}

	public Admin findAdminByUsername(String username) {
		//打开一个session
		SqlSession session = MyBatisUtil.getSession();
		Admin admin = null;
		try {
			
			admin = (Admin)session.selectOne(Admin.class.getName()+".findAdminByUsername", username);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			//关闭session
			session.close();
		}
		return admin;
	}

}
5.leadfar.cms.utils


package cn.com.leadfar.cms.utils;

import java.io.IOException;
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;

public class MyBatisUtil {
	static SqlSessionFactory factory = null;
	static{
		try {
			//通过配置文件,创建工厂对象
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			factory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	
	public static SqlSession getSession(){
		return factory.openSession();
	}
	
}


 
  
 
 

你可能感兴趣的:(ibatis又名(mybatis)使用方法,针对jdbc的封装)