MyBatis与Spring 整合

编写Spring配置文件




    
    

    
    
        
        
        
        
        
        
    

    
    
        
        
        
        
    

    
        
        
        
    

编写MyBatis配置文件





    
    
        
        
        
        
        
        
        
        
    

    
    
        
    

    
    
        

        
    

编写其他配置文件

日志配置文件"log4j.properties":

log4j.rootLogger = debug, stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %5p [%t] - %m%n

数据库资源文件"db.properties":

jdbc.driver=org.gjt.mm.mysql.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

使用Mapper代理

在pom.xml中添加:

   
        
        
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                
                false
            
            
                src/main/resources
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
    

在Spring全局配置文件applicationContext.xml中添加Spring的Mapper扫描器,用于扫描Mapper代理接口:

    
        
        
        
    

由于使用了spring的扫描类,所以Mapper配置文件要和Mapper代理接口位于一个包下,且名称一样。自动扫描出来的Mapper接口的bean的id为Mapper类名(首字母小写)。

新建UserQueryMapper.xml配置文件:





    

定义namespace下的Mapper代理接口:

package cn.com.sm.mapper;

import cn.com.sm.po.User;

public interface UserQueryMapper{
    public User findUserById(int id) throws Exception;
}

编写测试类:

package cn.com.sm.test;

import cn.com.sm.mapper.UserQueryMapper;
import cn.com.sm.po.User;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserMapperTest {
    private ApplicationContext applicationContext;

    @Before//是在执行本类所有测试方法之前先调用这个方法
    public void setup() throws Exception{
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    @Test
    public void testFindUserById() throws Exception{
        UserQueryMapper userQueryMapper=(UserQueryMapper)applicationContext.getBean("userQueryMapper");
        User user=userQueryMapper.findUserById(1);
        System.out.println(user.getId()+":"+user.getUsername());
    }
}

测试结果:

MyBatis与Spring 整合_第1张图片

你可能感兴趣的:(spring,mybatis)