Spring篇—Spring整合Mybatis完整讲解,一篇文章让你精通!

回顾Mybatis

一、编写实体类

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

二、编写实体类接口

//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
    //编写针对User表的相关操作,现在是查询用户
    public List<User> selectUser();
}

三、编写实体类接口对应的xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
    <select id="selectUser" resultType="user" parameterType="map">
        select * from mybatis.user
        <where>
            <if test="id !=null">
                id = #{id}
            </if>
        </where>
    </select>
</mapper>

四、编写Mybatis工具类

//Mybatis工具类
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //引入Mybatis核心配置文件路径
            String resource = "mybatis-config.xml";
            //通过Resources类读取核心配置文件,变成输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建SqlSessionFactoryBuilder对象,调用build方法创建sqlSessionFactory对象,专门用来开启sqlSession
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //通过sqlSessionFactory工厂,开启sqlSession
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

五、编写核心配置文件mybatis-config.xml,注册Mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!--    给实体类设置别名,用包扫描的方式,在这个包下面的实体类都默认别名为类名首字母小写-->
    <typeAliases>
        <package name="com.guohui.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!--            transactionManager表示事务管理-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--                在mybatis配置文件中的&符号要先进行转义,用&amp;-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;characterEncoding=utf8&amp;useUnicode=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--    每一个Mapper.xml文件都需要在我们的Mybatis核心配置文件中进行注册-->
    <mappers>
        <mapper resource="com/guohui/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

六、测试

public class MyTest {
   @Test
    public void test(){
       //获取SqlSession实例
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       //获取接口类,这样就可以直接调用接口中的方法
       UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       List<User> users = mapper.selectUser();
       for (User user : users) {
           System.out.println(user);
       }
       //会话结束,关闭sqlSession
       sqlSession.close();
   }
}

七、控制台

整合方式一

一、整合之前先在pom.xml中导入依赖
一定注意:导包一定要导版本适合的,不然不兼容,后面测试的时候就会报错

<dependencies>
    <!--        将Mybatis整合到Spring,先导包-->
    <!--        导入测试包-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--        导入数据库连接依赖-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!--        Mybatis依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.11</version>
    </dependency>
    <!--       spring-webmvc支持Spring功能依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <!--        AOP织入依赖-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <!--        Spring操作数据库,需要导入的依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>

    <!-- 整合Mybatis到Spring导入这个依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <!--        导入Lombok依赖-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
    </dependency>
</dependencies>
<!--配置resources,防止资源导出失败-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

二、编写spring-dao.xml配置文件(编写数据源、sqlSessionFactory、sqlSessionTemplate) 和mybatis-config.xml配置文件
1、spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--配置数据源DataSource:使用Spring的数据源替换掉Mybatis中的配置,
    我们现在使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
    这里我们能导入是因为我们pom.xml中导入了spring-jdbc的依赖-->
    <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/mybatis?useSSL=true&amp;characterEncoding=utf8&amp;useUnicode=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--    配置sqlSessionFactory,将数据源通过set方法注入到sqlSessionFactory中-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--    绑定Mybatis配置文件,name是写死的用configLocation,作用是将这个配置文件和mybatis-config.xml关联-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--    配置注册Mapper.xml文件-->
        <property name="mapperLocations" value="classpath:com/guohui/mapper/*.xml"/>
    </bean>

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

</beans>

2、mybatis-config.xml配置文件,此时已经和spring-dao.xml关联

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!--    给实体类设置别名,用包扫描的方式,在这个包下面的实体类都默认别名为类名首字母小写-->
    <typeAliases>
        <package name="com.guohui.pojo"/>
    </typeAliases>
<!--将来养成习惯,在Mybatis核心配置文件中仅仅配置别名还有一些setting设置即可-->
<!--    <settings>-->
<!--        <setting name="" value=""/>-->
<!--    </settings>-->
</configuration>

三、编写实体类、实体类接口、Mapper.xml文件,另外需要给接口增加实现类
1、实体类

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

2、实体类接口

//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
    //编写针对User表的相关操作,现在是查询用户
    public List<User> selectUser(Map map);
}

3、Mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
    <select id="selectUser" resultType="user" parameterType="map">
        select * from mybatis.user
        <where>
            <if test="id !=null">
                id = #{id}
            </if>
        </where>
    </select>
</mapper>

4、接口实现类

public class UserMapperImpl implements UserMapper{
    //现在我们使用SqlSessionTemplate取代了sqlSession
    private SqlSessionTemplate sqlSession;

    //编写set方法,便于在spring-dao.xml配置文件中用set方法注入Bean
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    //现在我们将Mybatis和Spring进行整合以后,直接调用方法,就能直接实现对数据库的操作
    @Override
    public List<User> selectUser(Map map) {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser(map);
    }
}


四、编写一个applicationContext.xml核心配置文件,将来的Dao或者MVC的配置文件都可以通过import关键字来导入,注册我们编写的实现类

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    导入Dao配置文件-->
 <import resource="spring-dao.xml"/>


    <!--    注册UserMapperImpl.java实现类-->
    <bean id="sqlSession" class="com.guohui.mapper.UserMapperImpl">
        <!--        将SqlSessionTemplate类型的sqlSession通过set方法注入到UserMapperImpl实现类中-->
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>
</beans>

五、测试

public class MyTest {
   @Test
    public void test(){
       //获取Spring容器
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       //我们现在只需要创建UserMapperImpl实现类的对象,调用里面的方法即可,注意,最后的类型要是接口的类型
       UserMapper sqlSession = context.getBean("sqlSession", UserMapper.class);
       Map<Object, Object> map = new HashMap();
       map.put("id",1);
       for (User user : sqlSession.selectUser(map)) {
           System.out.println(user);
       }
   }
}


六、控制台

七、总结
通过Spring将Mybatis整合,工厂和sqlSession的创建不用在测试类中去新建,也不用专门写一个工具类获取sqlSession,我们只需要在spring-dao.xml中对工厂factory和sqlSessionTemplate进行配置,然后在多写一个实现类实现dao接口中的方法,我们在调用的时候直接调用方法,无需在获取sqlSession

整合方式二

一、编写实体类

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

二、编写对应的接口

//User的Dao接口,我们将来的编码习惯就用mapper
public interface UserMapper {
    //编写针对User表的相关操作,现在是查询用户
    public List<User> selectUser(Map map);
}


三、编写Mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace需要和我们的Dao/Mapper接口进行绑定才能产生关联,里面就写接口类就行-->
<mapper namespace="com.guohui.mapper.UserMapper">
    <select id="selectUser" resultType="user" parameterType="map">
        select * from mybatis.user
        <where>
            <if test="id !=null">
                id = #{id}
            </if>
        </where>
    </select>
</mapper>

四、配置spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--配置数据源DataSource:使用Spring的数据源替换掉Mybatis中的配置,
    我们现在使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource
    这里我们能导入是因为我们pom.xml中导入了spring-jdbc的依赖-->
    <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/mybatis?useSSL=true&amp;characterEncoding=utf8&amp;useUnicode=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!-- 配置sqlSessionFactory,将数据源通过set方法注入到sqlSessionFactory中-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--    绑定Mybatis配置文件,name是写死的用configLocation,作用是将这个配置文件和mybatis-config.xml连接-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--    配置注册Mapper.xml文件-->
        <property name="mapperLocations" value="classpath:com/guohui/mapper/*.xml"/>
    </bean>

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

</beans>

五、编写接口的实现类

/*
整合方式二:通过继承SqlSessionDaoSupport,为我们提供一个getSqlSession(),可以获取到SqlSessionTemplate
获取到之后,就可以直接调用getMapper方法,然后对数据库进行操作了
*/

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {

    @Override
    public List<User> selectUser(Map map) {
        return getSqlSession().getMapper(UserMapper.class).selectUser(map);
    }
}


六、将实现类在Spring中注册

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    导入Dao配置文件-->
 <import resource="spring-dao.xml"/>


    <!--    注册UserMapperImpl.java实现类-->
    <bean id="sqlSession" class="com.guohui.mapper.UserMapperImpl">
        <!--        将SqlSessionTemplate类型的sqlSession通过set方法注入到UserMapperImpl实现类中-->
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>

<!--    注册注册UserMapperImpl2-->
    <bean id="sqlSession2" class="com.guohui.mapper.UserMapperImpl2">
<!--由于我们继承的SqlSessionDaoSupport类中需要sqlSessionFactory,并且存在set方法,直接进行注入即可-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

七、测试
 

public class MyTest {
   @Test
    public void test(){
       //获取Spring容器
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       //我们现在只需要创建UserMapperImpl实现类的对象,调用里面的方法即可,注意,最后的类型要是接口的类型
       UserMapper sqlSession = context.getBean("sqlSession2", UserMapper.class);
       Map<Object, Object> map = new HashMap();
       map.put("id",1);
       for (User user : sqlSession.selectUser(map)) {
           System.out.println(user);
       }
   }
}

八、控制台

至此,你已经深入的理解了Spring如何去整合Mybatis,并且对实现的原理也已经掌握,后续会继续更新,欢迎交流和指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Be explorer

若认可笔者文章,手头富裕望支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值