> 文章列表 > Spring 03 -Spring-Mybaits整合

Spring 03 -Spring-Mybaits整合

Spring 03 -Spring-Mybaits整合

Spring-Mybaits整合

  • 先上核心配置总结`模版套用就完事了`
  • 以下是细分示例
    • Spring与Mybaits
      • 1.1 导入依赖
      • 1.2 配置SqlSessionFactory
      • 1.3 配置MapperScannerConfigurer
      • 1.4 配置Service
      • 1.5 测试
    • 2 Spring细节补充
      • 2.1 导入外部配置文件
      • 2.2 将配置文件分离
      • 2.3 Spring整合Mybatis后的日志
    • 3 Spring整合Junit
    • 4 纯注解开发

先上核心配置总结模版套用就完事了

将 SqlSessionFactory、Mapper、Service 都交给SpringIOC容器管理

  1. 导入依赖

  2. applicationContext.xml配置 (mybatis全部拿到applicationContext里面)

    1. 开启Spring注解扫描 <context:component-scan base-package="com.ying"/>

    2. 引入外部的配置文件 <context:property-placeholder location="classpath:db.properties"/>

    3. 创建Druid连接池对象<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

      ​ druid连接配置

    4. SqlSessionFactoryBean对象 处理Mybatis相关对象

      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

      ​ 属性注入

      1. 注入数据源(必须)<property name="dataSource" ref="dataSource"/>

      2. mybatis配置

        1. mybatis核心配置文件

          1. 第一种:配置一个mybatis核心配置文件,然后在这里引用(在xml配置文件中引入其他的配置文件需要加上classpath:) <property name="configLocation" value="classpath:mybatis-config.xml"></property>
          2. 第二种:mybatis的核心配置文件可以不用写了,直接在spring中进行属性注入
        2. 类型别名配置 <property name="typeAliasesPackage" value="com.ying.pojo"/>

        3. mapper映射文件配置<property name="mapperLocations" value="com/ying/mapper/*.xml"/>关联com/ying/mapper文件夹下所有的mapper映射文件

        4. settings配置 <property name="configuration" ref="configuration"/>

        5. plugins配置

          <property name="plugins">

          <bean class="com.github.pagehelper.PageInterceptor">

          </bean></property>

    5. configuration <bean…><bean id="configuration" class="org.apache.ibatis.session.Configuration">

      1. 日志配置 开启mybatis自带的日志 <property name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"/>
      2. 全局懒加载配置 <property name="lazyLoadingEnabled" value="true"></property>
    6. MapperScannerConfigurer将所有的Mapper添加到SpringIOC容器中

      1. Mapper是接口(接口不能创建对象):Mybatis的底层用到了动态代理技术,会创建Mapper接口的实现类

      2. MapperScannerConfigurer:将所有的Mapper接口的实现类添加到SpringIoc容器中

        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--如果以后Mapper映射文件与Mapper接口在同一级目录,那么就无需指定--><property name="basePackage" value="com.sun.mapper"/>
        </bean>
        

以下是细分示例

Spring与Mybaits

1.1 导入依赖

<dependencies><!--   持久层依赖 数据库相关     --><!--   数据库驱动依赖     --><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.4</version></dependency><!--   druid连接池依赖     --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><!--  Spring依赖     --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.6</version></dependency><!--  Spring和Mybatis整合依赖     --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.2</version></dependency><!--  Spring整合持久层依赖     --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.6</version></dependency><!--  其他依赖     --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version></dependency>
</dependencies>

1.2 配置SqlSessionFactory

<!--  SqlSessionFactoryBean用来整合Mybatis的类  -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--    配置mybatis数据源连接池    --><property name="dataSource" ref="dataSource"/><!--    配置mybatis的配置信息    --><!--    <property name="typeAliasesPackage" value="com.ying.pojo"/>  --><!--    <property name="mapperLocations" value="classpath:com/ying/mapper/*.xml"/>  --><!--    加载mybatis的配置文件    --><property name="configLocation" value="classpath*:mybatis-config.xml"/>
</bean>

1.3 配置MapperScannerConfigurer

管理创建Mapper对象,存入工厂管理

  • 扫描所有Mapper接口,去构建Mapper实现

  • 将Mapper实现存入工厂管理

  • Mapper实现对象在工厂中的id是:“首字母小写的-接口的类名”,

    例如:UseMapper==>userMapper , OrderMapper==>orderMapper

<!--    MapperScannerConfigurer扫描所有的mapper映射文件,并且将Mapper接口创建并交给Spring容器  (要保证接口和映射的名称一致、路径一致)  
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.ying.mapper"/>
</bean>

1.4 配置Service

@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper mapper;@Overridepublic List<User> getAll() {return mapper.getAll();}
}

1.5 测试

public class SMTest {@Testpublic void test01(){ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");UserServiceImpl userServiceImpl = ac.getBean("userServiceImpl", UserServiceImpl.class);List<User> userList = userServiceImpl.getAll();userList.stream().forEach(System.out::println);}
}

2 Spring细节补充

2.1 导入外部配置文件

db.propertis

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///java2101
jdbc.username=root
jdbc.password=123456

applicationContext.xml

<!-- 引入外部的配置文件  -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 获取外部的配置文件中的属性值  格式:${key}    注意:不能使用username --><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>

2.2 将配置文件分离

applicationContext.xml Spring主配置文件

applicationContext-dao.xml Spring整合Mybatis的配置文件

applicationContext-xxx.xml 未来Spring整合其他技术的配置文件

applicationContext.xml

<!-- 引入其他Spring的配置文件   -->
<!--整合Mybatis -->
<import resource="classpath:applicationContext-dao.xml"/>

applicationContext-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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- 引入外部的配置文件  --><context:property-placeholder location="classpath:db.properties"/><!-- Spring整合Mybatis   --><!-- 配置Druid数据源   --><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><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 配置数据源   --><property name="dataSource" ref="dataSource"/><!-- mybatis的配置   --><property name="configLocation" value="classpath:mybatis-config.xml"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.ying.mapper"/></bean>
</beans>

2.3 Spring整合Mybatis后的日志

Mybatis核心配置文件

<configuration><!--  设置mybatis日志    --><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings><!--  设置类型别名    --><typeAliases><package name="com.ying.pojo"/></typeAliases>
</configuration>

Spring配置文件中引入

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 配置数据源   --><property name="dataSource" ref="dataSource"/><!-- mybatis的配置 --><property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

3 Spring整合Junit

导入依赖

<!--  Spring单元测试依赖  -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.6</version>
</dependency>

测试类

@RunWith(SpringJUnit4ClassRunner.class)  //使用Spring来执行单元测试
@ContextConfiguration("classpath:applicationContext.xml") //加载spring的配置文件
public class SMTest {@Autowiredprivate UserService userService;@Testpublic void test01(){List<User> userList = userService.getAll();userList.stream().forEach(System.out::println);}
}

4 纯注解开发


常见的注解(还有上面的几个注解):

  • @Configuration 表示当前这个类是Spring配置类
  • @ComponentScan 扫描指定包上的注解
  • @Import 引入其他的配置类
  • @Bean 将创建的对象添加到SpringIOC容器
  • @Value 将值注入到属性中
  • @PropertySource 导入外部的Properties配置文件键

主配置类

@Configuration   // 表示当前这个类是一个spring配置类(相当于applicationContext.xml)
@ComponentScan("com.ying")   //开启注解扫描
@Import(MybatisConfiguration.class)  //引入其他的spring的配置类
public class SpringConfiguration {
}

Spring整合Mybatis配置类

@Configuration
@PropertySource(value={"classpath:db.properties"})
@Import(MapperScannerConfigurerConfiguration.class)
public class MybatisConfiguration {@Value("${jdbc.driver}") //获取配置文件中值,并且注入变量private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Bean("dataSource")   //将当前方法返回的对象交给Spring容器public DataSource getDataSource(){DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName(driver);druidDataSource.setUrl(url);druidDataSource.setUsername(username);druidDataSource.setPassword(password);return druidDataSource;}@Beanpublic SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();//设置数据源sqlSessionFactoryBean.setDataSource(dataSource);//设置Mybatis的信息sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));return sqlSessionFactoryBean;}
}

因为配置文件加载顺序问题,所以需要将 MapperScannerConfigurer对象单独配置

@Configuration
public class MapperScannerConfigurerConfiguration {@Beanpublic MapperScannerConfigurer getMapperScannerConfigurer(){MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.ying.mapper");return mapperScannerConfigurer;}
}

或者直接使用@MapperScan(“com.ying.mapper”)注解代替MapperScannerConfigurer类

@Configuration
@PropertySource(value={"classpath:db.properties"})
@MapperScan("com.ying.mapper")
public class MybatisConfiguration {@Value("${jdbc.driver}") //获取配置文件中值,并且注入变量private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Bean("dataSource")   //将当前方法返回的对象交给Spring容器public DataSource getDataSource(){DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName(driver);druidDataSource.setUrl(url);druidDataSource.setUsername(username);druidDataSource.setPassword(password);return druidDataSource;}@Beanpublic SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();//设置数据源sqlSessionFactoryBean.setDataSource(dataSource);//设置Mybatis的信息sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));return sqlSessionFactoryBean;}
}