spring整合mybatis(下篇)

106 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

在上篇已经完成了mybatis环境的搭建并做了简单测试,下篇内容就如何整合mypatis进行详细讲解。

1. spring基础环境

做spring开发首先要到pom.xml中导入spring依赖的坐标,我已经做好了整理,如下:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.2.10.RELEASE</version>
</dependency>
<!--MyBatis-Spring的依赖-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>2.0.7</version>
</dependency>

基础pom环境构建好后我们需要新建一个spring的xml文件,刚生成的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 http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

xml中配置spring的bean比较繁琐,所以这里我用了spring注解包来管理我要用到的bean,所以修改配置文件,导入spring注解包,如下。我个人是比较喜欢这种半配置的开发,半配置形式开发可以让我们在开发中少做些思考,直接丢进配置完事儿。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	 <!--扫描com.itheima包及其子包下的类中注解-->
    <context:component-scan base-package="com.itheima"/>
</beans>

另外数据源配置部分我用的是加载properties文件的方法,以后数据库修改了密码,直接改这个配置文件就行了,比上篇那种写死的硬编码强多了。加载properties文件首先要导一个扫描properties的包,如下写如你的spring配置文件就行。

<!--扫描propertise文件-->
<context:property-placeholder location="sqlconfig.properties"/>

然后xml里面写入我们的dataSourse数据源的配置,如下;

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

之前mybatis配置文件里的数据源这块内容就可以删掉了,我的propertise配置文件内容如下图。涉及隐私,账号密码部分就码掉了。

image.png 然后我们打开官网,跟着官网做一下bean工厂的配置,如下。这块其实实现的功能就类似于我们做mybatis开发的时候,前几行要写加载配置的代码。

image.png 我们上篇写到的mapper接口代码改成下面这个样子,这是mybatis用注解写sql的方法。

public interface accountMapper {
    @Select("select * from tbl_account")
    List<Accountor> selectAll();
}

到现在为止呢我们mybatis的数据源部分的配置文件已经可以删掉了,也就是对应下图红框部分。

image.png 然后我们在spring的xml文件夹做一下mapper的映射。

<bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.springmybatis.mapper.accountMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

这里做完,我们就可以删掉所有mybatis的配置相关代码了。 整合后运行结果这些。


image.png