Dao层整合也就是整合Spring和MyBatis:把MyBatis要用的数据源和SqlSessionFactory交给Spring管理
整合S M 的配置文件应该放在哪呢? 是放在dao中还是放在service中呢?
答案是放在service中,因为dao,interface,pojo工程最终是要打成jar包放到service工程的WEB-INF/lib目录下的,配置文件放到jar包中读取不方便,所以选择放到service工程中
先配置myBatis的配置文件
这个配置文件中什么都不需要配,它的作用是后期配置SqlSessionFactory时,要有myBatis的核心配置文件
然后配置Spring的配置文件,applicationContext-dao.xml
这个配置文件的任务是:配置数据源,SqlSessionFactoryBean,Mapper映射文件包扫描器。
为方便复制,代码贴出来
<?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:p="http://www.springframework.org/schema/p" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:properties/db.properties" /> <!-- 配置数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <property name="maxActive" value="10" /> <property name="minIdle" value="5" /> </bean> <!-- 配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <!-- Mapper映射文件的包扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.taotao.mapper" /> </bean> </beans>
在配置applicationContext-dao.xml时,用到了一个配置文件db.properties
所以现在我们新建一个db.properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/taotao jdbc.username=root jdbc.password=root
谨记peoperties文件中不能带空格,不论空格出现在哪都会出错