代码层次

Spring和Mybatis的整合.jpg

整合

mybatis:dao层,操作数据库,需要单例的SqlSessionFactory工厂。 spring:容器,管理对象。 可以将SqlSessionFactory、事务、连接池以及mapper的动态代理交给spring来做。

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/spring-aop.xsd">

    <!--加载外部资源文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置SqlSessionFactory,通过Spring来管理会话工厂-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源:因为要使用SqlSession操作数据库-->
        <property name="dataSource" ref="dataSource"></property>
        <!--加载mybatis的全局配置文件-->
        <!--<property name="configLocation" value="classpath:mybatis.xml"></property>-->
        <!--Spring起别名-->
        <property name="typeAliasesPackage" value="com.me.pojo"></property>
    </bean>

    <!--mapper动态代理 通过扫描批量加载mapper接口来创建代理bean,这些bean的名字是接口名字(首字母小写)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定mapper接口的包路径-->
        <property name="basePackage" value="com.me.mapper"/>
    </bean>

    <!--注解扫描-->
    <context:component-scan base-package="com.me.service"></context:component-scan>
</beans>

UsersService.java

public interface UsersService {
    public Users selectById(int id);
}

UsersServiceImpl

@Service("userService")
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Users selectById(int id) {
        return usersMapper.selectById(id);
    }
}

测试类

public class AppTest {
    @Test
    public void selectById(){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        UsersService usersService= (UsersService) applicationContext.getBean("userService");
        Users user=usersService.selectById(1);
        System.err.println(user.getUsername());
    }
}