Mybatis+Spring框架整合

1.整合思路

1、SqlSessionFactory对象应该放到spring容器中作为单例存在。

2、传统dao的开发方式中,应该从spring容器中获得sqlsession对象。

3、Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。

4、数据库的连接以及数据库连接池事务管理都交给spring容器来完成。

2. 整合需要的jar包

1、spring的jar包

2、Mybatis的jar包

3、Spring+mybatis的整合包。

4、Mysql的数据库驱动jar包。

数据库连接池的jar包

3. 整合的步骤

1. 创建工程

2. 导入jar包

3. 加入配置文件

1. mybatisSpring的配置文件sqlmapConfig.xml

2.Spring的配置文件applicationContext.xml

a)        数据库连接及连接池

b)        事务管理(暂时可以不配置)

c)        sqlsessionFactory对象,配置到spring容器中

d)        mapeer代理对象或者是dao实现类配置到spring容器中。

1.1.3.1. SqlMapConfig.xml

配置文件是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>
        
        <package name="cn.itcast.mybatis.pojo" />
    typeAliases>

configuration>

1.1.3.2. applicationContext.xml

SqlSessionFactoryBean属于mybatis-spring这个jar包

applicationContext.xml,配置内容如下

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

   
   <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>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        
        <property name="dataSource" ref="dataSource" />
    bean>
beans>

1.1.3.3. db.properties

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

1.1.3.4. 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

1.1.3.5. 效果:

加入的配置文件最终效果如下:

Mybatis+Spring框架整合_第1张图片

4.mapper代理开发dao

4.1. 实现Mapper.xml

编写UserMapper.xml配置文件,如下:

xml version="1.0" encoding="UTF-8" ?>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">
    
    <select id="queryUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    select>

    
    <select id="queryUserByUsername" parameterType="string"  resultType="user">
        select * from user where username like '%${value}%'
    select>

    
    <insert id="saveUser" parameterType="user">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
            select last_insert_id()
        selectKey>
        insert into user
        (username,birthday,sex,address) values
        (#{username},#{birthday},#{sex},#{address})
    insert>
mapper>

4.2. 实现UserMapper接口

public interface UserMapper {
    /**
     * 根据用户id查询
     * 
     * @param id
     * @return
     */
    User queryUserById(int id);

    /**
     * 根据用户名模糊查询用户
     * 
     * @param username
     * @return
     */
    List queryUserByUsername(String username);

    /**
     * 添加用户
     * 
     * @param user
     */
    void saveUser(User user);
}

4.3. 方式一:配置mapper代理

在applicationContext.xml添加配置

MapperFactoryBean也是属于mybatis-spring整合包(封装了准备工作,但是需要提供工厂与接口)


<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    
    <property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper" />
    
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
bean>

4.4. 测试方法

public class UserMapperTest {
    private ApplicationContext context;

    @Before
    public void setUp() throws Exception {
        this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    @Test
    public void testQueryUserById() {
        // 获取Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        User user = userMapper.queryUserById(1);
        System.out.println(user);
    }

    @Test
    public void testQueryUserByUsername() {
        // 获取Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        List list = userMapper.queryUserByUsername("张");

        for (User user : list) {
            System.out.println(user);
        }
    }
    @Test
    public void testSaveUser() {
        // 获取Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        User user = new User();
        user.setUsername("曹操");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("三国");

        userMapper.saveUser(user);
        System.out.println(user);
    }
}

4.5. 方式二:扫描包形式配置mapper(无需配置工厂与接口,自动扫描)


<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    
    <property name="basePackage" value="cn.itcast.mybatis.mapper" />
bean>

每个mapper代理对象的id就是类名,首字母小写

 

你可能感兴趣的:(Mybatis+Spring框架整合)