SSM整合配置详解 (Spring——MyBatis)

/**导入架包
配置文件
conf.xml(mybatis)



	
	
        
	
	
	
	




mapper(mybatis)
applicationContext.xm(Spring
applicationContext.xm(Spring)



	
		
		
		
		
	

	
		
		
		
	
	针对mybatis的
	
		
		
		
	
	
	
		
	

	
		
	
	

	
		
	
1
1
持久层实现类比如现在有个UserDaoImpl
package com.project.dao.impl;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.project.bean.UserBean;
import com.project.dao.IUserDao;

public class UserDaoImpl implements IUserDao{

	private SqlSessionFactory fa;
	
	//要给 SqlSessionFactory提供set方法,因为我们要在applicationContext.xml中将             //SqlSessionFactory注入给userDaoImpl实现类
	public void setFa(SqlSessionFactory fa) {
		this.fa = fa;
	}
	@Override
	public void login() {
		
		System.out.println("正在进行登录");
		
	}
	@Override
	public void register() {
		
		System.out.println("正在进行注册");
		
	}
	@Override
	public void findAll() {
		System.out.println("正在获取所有的用户信息");
		
	}
//通过工厂产生session
	@Override
	public UserBean findById(int id) {
		SqlSession session = fa.openSession();
		UserBean bean=null;
		try {
			IUserDao dao = session.getMapper(IUserDao.class);
			bean = dao.findById(id);

			
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			session.close();
		}
		return bean;
	}
}

1
新建一个测试类TestMain
package com.project.test;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.project.bean.UserBean;
import com.project.dao.IUserDao;
import com.project.dao.impl.UserDaoImpl;

public class TestMain {
	@Test
	public void test(){
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		/*
		 * 区别:
		 * getBean(IUserDao.class.xxx)
		 * getBean("xxx")
		 *  
		 *  
		 *  采用aop编程,获取到的动态代理对象,jdk?cglib
		 *  
		 *  代理的对象如果有接口,默认使用jdk动态代理
		 *  代理的对象没有接口是pojo类,使用cglib动态代理
		 * */
		IUserDao dao = (IUserDao) context.getBean("userdao2");
		
		dao.login();
		dao.register();
		System.out.println("======");
		dao.findAll();
		//dao.findById();
		
		UserBean bean = (UserBean) context.getBean("userbean");
		System.out.println(bean);
	}
	
	@Test
	public void test2(){
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		IUserDao dao = (IUserDao) context.getBean("userDaoImpl");
		
		UserBean bean = dao.findById(1);
		System.out.println(bean);
	}
}

*/


			   				

 

你可能感兴趣的:(Spring,MyBtis,SSM)