20.0、spring和mybatis的整合

20.0、Spring和Mybatis的整合

首先说一下未整合之前的mybatis配置,这样可以更好的对比学习整合之后的内容

未整合之前的,Mybatis-config.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="com.hkl.gamesocialization.core.po" />
    </typeAliases>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis001" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
</environments>

</configuration>

整合mybatis和spring就两步:

1.导入相应的包

·Junit

·mybatis

·MySQL数据库

·spring相关的

·aop织入

·mybatis-spring【new】

2.配置mybatis文件,连接数据库

所以我们先来导入相关依赖

pom.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Part4_1</artifactId>
        <groupId>cn.edu.hziee</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-10-mybatis</artifactId>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
    </dependencies>
<!--静态资源导出问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

</project>

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--DataSource:使用Spring的数据源替换MyBatis的配置  c3p0  dbcp  druid-->
    <!--我们这里使用Spring提供的JDBC : org.springframework.jdbc.datasource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springmvctest?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--        绑定Mibatis配置文件-->
        <property name="configuration" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/hkl/mapper/*.xml"/>
    </bean>

<!--    SqlSessionTemplate:就是我们使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能使用构造器注入sqlSessionFactory,因为他没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="userMapper" class="com.hkl.mapper.UserMapperIpml">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

Usermapper.java文件

package com.hkl.mapper;

import com.hkl.pojo.User;

import java.util.List;

public interface Usermapper {
    public List<User> selectUser();
}

UserMapperIpml.java文件

package com.hkl.mapper;

import com.hkl.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperIpml implements Usermapper {
    //我们所有的操作,都使用sqlSession来执行在原来,现在都是用SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUser() {
        Usermapper mapper = sqlSession.getMapper(Usermapper.class);
        return mapper.selectUser();
    }

}

测试类test.java文件方法调用

import com.hkl.mapper.Usermapper;
import com.hkl.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

public class test {
    @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Usermapper usermapper = context.getBean("userMapper",Usermapper.class);
        for(User user : usermapper.selectUser()) {
            System.out.println(user);
        }
    }
}

        未整合之前数据源由mybatis来配置管理,

        整合之后我们将数据源移交给spring容器来配置管理,这样我们在测试文件中就不用手动的去创建数据源、SqlSessionFactory和SqlSession了,这些东西全部可以交给Spring去创建和管理。

        在Spring配置中我们需要配置:

                ·数据源

                ·SqlSessionFactory

                ·SqlSessionTemp(这个其实就是SqlSession只是换了个名字)

然后需要手动将该构造器的方法注入一下SqlSessionFactory参数

        然后与mybatis不同的是整合之后需要创建一个mapper接口的实现类这个实现类中需要有一个

Sqlsession的set注入方法,(因为Spring是面向对象可以这么理解所以需要一个类来完成)将这个

实现类bean注册到Spring的配置文件中,用property来完成实现类中set方法的注入,就像applicationcontex.xml配置文件最后一段一样将实现类导入容器中

然后直接在测试类中(以下是伪代码) :

ApplicationContext context = new ...(“ApplicationContext.xml”);
UserMaaperImpl u = Context.getBean(“UserMaaperImpl”,UserMaaperImpl.Class);
u.SelesctUserList();

下面再来看看如果使用之前的mybatis来管理数据源的话,该如何调取数据,以及他的缺点

MyTest.java测试文件

import com.hkl.mapper.Usermapper;
import com.hkl.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyTest {
    @Test
    public void test() throws IOException {
        String resources = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resources);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);

        Usermapper usermapper = sqlSession.getMapper(Usermapper.class);
        List<User> userList = usermapper.selectUser();
        for(User user : userList) {
            System.out.println(user);
        }
    }
}

如上述代码所示如果只是用mybatis来管理数据源的话,调用方法时必须先获取数据源、然后获取sqlsessionFactory、SqlSesssion等对象才能调用,十分繁琐麻烦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值