首先我们建一个连接数据库的配置文件jdbc.properties
其中需要你配置的有你的数据库名,用户名和密码。需要注意的是mysql8.0以后的版本的连接方式改变了。本文用的是8.0以后的版本,如果是8.0之前的版本,需要你对driverClassName和url做出修改。
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/你的数据库名?characterEncoding\=utf8&useSSL\=false&serverTimezone\=UTC&allowPublicKeyRetrieval\=true
username=你的用户名
password=你的密码
spring-mybatis.xml的配置。该文件一次性将spring和spring联合mybatis的配置文件全部完成。
1.表头
<?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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
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-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
</beans>
2.将数据库配置文件jdbc.properties添加进来。
<context:property-placeholder location="classpath:jdbc.properties" />
3.此配置直接可以将AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor一次性配置结束。
<context:annotation-config />
4.连接数据库,本次使用的druid连接池,引入druid依赖后即可使用,其他还有传统jdbc,c3p0连接池等连接方式。因为初学,所以我们并没有使用其他更多的功能。
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
5. 配置sqlSessionFactory,在这里我们注入了数据库连接池,扫描并注入了mapper.xml和dao层数据,其中dao层使用别名,具体好处我们写mapper.xml时就能感受到。
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations"
value="classpath:com/bookstore/mapper/*Mapper.xml" />
<!-- 扫描domain包 使用别名 -->
<property name="typeAliasesPackage" value="com.bookstore.dao" />
</bean>
6.在这一步将spring和mybatis整合
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 给出需要扫描mapper接口包 -->
<property name="basePackage" value="com.bookstore.mapper" />
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
7.扫描service层
<context:component-scan base-package="com.bookstore.service"></context:component-scan>
8.事务管理方面(本人还有待了解)
<!-- 5.配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 6.注解方式配置事物 -->
<tx:annotation-driven transaction-manager="transactionManager" />