Mybatis基础系列(三)

一、整合思路

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

二、整合步骤

Spring配置文件:

<context:property-placeholder location="classpath:db.properties"/>

<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="10" />
    <property name="maxIdle" value="5" />
</bean>
<!-- Mybatis的工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!-- 核心配置文件的位置 -->
    <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
<!-- Mapper动态代理开发方式一 -->
<!-- 根据工厂和接口生成实现类 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    <property name="mapperInterface" value="com.long.mapper.UserMapper"/>
</bean>
<!-- Mapper动态代理开发方式二扫描,自动找到sqlSessionFactory-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 基本包 -->
    <property name="basePackage" value="com.long.mybatis.mapper"/>
</bean>

UserMapper接口:

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

UserMapper.xml:

<mapper namespace="com.long.mapper.UserMapper">
    <!-- 通过ID查询一个用户 -->
    <select id="findUserById" parameterType="Integer" resultType="User">
        select * from user where id = #{v}
    </select>
</mapper>

sqlmapConfig.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.long.mybatis.pojo" />
    </typeAliases>
    <mappers>
        <package name="com.long.mybatis.mapper"/>
    </mappers>

</configuration>

测试:

public class JunitTest {
    @Test
    public void testMapper() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper mapper = ac.getBean(UserMapper.class);
//      UserMapper mapper = (UserMapper) ac.getBean("userMapper");
        User user = mapper.findUserById(10);
        System.out.println(user);
    }
}

转载请标明出处,原文地址:https://blog.csdn.net/weixin_41835916
总结整理不容易,如果觉得本文对您有帮助,请点击支持一下,您的支持是我写作最大的动力,谢谢。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41835916/article/details/80907156
今日推荐