1.前言
spring和mybatis都是现在最流行的框架,他们能解决不同的问题。这里介绍spring和mybatis的整合方案,进一步简化项目的目录结构,也可以少写一个配置文件。
2.配置文件
2.1创建jdbc的属性文件
为了解耦,最好不要将数据库的关键信息写死在配置文件中,创建一个properties文件保存数据库信息是最好的
jdbc.properties
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=*******
jdbc.password=********
2.2配置文件
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:mybatis/jdbc.properties"/>
<!-- 数据源封装类,数据源:获取数据库连接 这个类在spring-jdbc中-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
<!-- 创建sqlsessionfactory,在mybatis-spring包中 ,这里面使用了上面的datasource来生成对象-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 给bean目录下的所有的类起别名 -->
<property name="typeAliasesPackage" value="bean"></property>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- 配置mapper映射 ,这个类在mybatis-spring中,相当于mybatis配置文件中的mapper标签
用于扫描某个包下的mapper文件-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="dao"></property>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>
</beans>
2.3配置web.xml
在这里配置web.xml文件,使得tomcat启动时自动加载配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-service.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
项目启动之后,spring会自动根据mybatis的配置生成mybatis中的接口的对象,所以我们不在需要使用sqlsessionfactory和sqlsession来操作sql语句和数据库,比以前会方便很多