Mybatis学习笔记(八)--整合spring

一.整合思路

  1. SqlSessionFactory对象应该放到spring容器中作为单例存在。
  2. 传统dao的开发方式中,应该从spring容器中获得sqlsession对象。
  3. Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。
  4. 数据库的连接以及数据库连接池事务管理都交给spring容器来完成。

二.需要的jar包

  1. spring的jar包
  2. Mybatis的jar包
  3. Spring+mybatis的整合包。
  4. Mysql的数据库驱动jar包。
  5. 数据库连接池的jar包

Mybatis学习笔记(八)--整合spring_第1张图片

ps:需要jar可以留言邮箱,博主会发给你,后期代码上传到Github,大家可以去clone或者下载!!!

程序目录

Mybatis学习笔记(八)--整合spring_第2张图片

三.配置applicationContext.xml文件




	
	
	
	
	
		
		
		
		
		
		
	
	
	
	
		
		
		
	
	
	
	 
	 
	 
	  
	  	
		
		
		
	
	

四.配置jdbc.properties与log4j.properties文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

五.配置sqlMapConfig.xml文件




    
	
		
	
    
	
		
	

六.Mapper.xml与UserMapper.java




	
	
package com.janson.mapper;

import com.janson.pojo.User;

public interface UserMapper {
	
	public User findUserById(Integer id);

}

七.测试代码

package com.janson.test;

import static org.junit.Assert.*;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.janson.mapper.UserMapper;
import com.janson.pojo.User;

public class MybaitsAndSringTest {

	//非增强版的测试  导入的是接口的地址
	@Test
	public void findUserByIdTest() throws Exception {
		//获得spring
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserMapper mapper = (UserMapper) context.getBean("userMapper");
		User user = mapper.findUserById(2);
		System.out.println(user);
	}
	
	//非增强版的测试  导入的是接口的地址
	@Test
	public void findUserByIdTest2() throws Exception {
		//获得spring
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserMapper mapper = context.getBean(UserMapper.class);
		User user = mapper.findUserById(2);
		System.out.println(user);
	}
	
}

八.测试结果

你可能感兴趣的:(Mybatis)