整合Dao层
mybatis整合spring,通过spring管理SqlSessionFactory、mapper代理对象。
- 使用mybatis框架,须创建该框架的核心配置文件——SqlMapConfig.xml。
- 使用spring框架,须创建一个applicationContext-dao.xml配置文件,该文件的内容有:
- 配置数据源。
- 需要让spring容器管理SqlsessionFactory,其是单例存在的。
- 把mapper的代理对象放到spring容器中,使用扫描包的方式加载mapper的代理对象。
1)添加db.properties配置文件
在classpath(src/main/resource)目录下新建一个properties文件夹,然后在该目录下新建一个db.properties文件:
#mysql的驱动
jdbc.driver=com.mysql.jdbc.Driver
#连接地址
jdbc.url=jdbc:mysql://localhost:3306/xiyuyou?useUnicode=true&characterEncoding=UTF-8
#连接用户名
jdbc.username=root
#连接密码
jdbc.password=123456
2)配置MyBatis核心文件
在src/main/resources目录下新建mybatis文件夹,然后创建一个SqlMapConfig.xml配置文件:
我们暂时不用向里面添加任何配置,像数据库连接池、事务之类的配置会交给Spring来管理,别名可配可不配,因此我们这里就放一个只有头的空文件就可以了(文件虽然没有配置任何内容,但是不能没有)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
3)配置spring-dao.xml文件
在src/main/resources目录下新建一个spring文件夹,然后在该文件夹下新建一个applicationContext-dao.xml文件:
我们在applicationContext-dao.xml文件当中配置数据库连接池、SqlSessionFactory(Mybatis的连接工厂)、Mybatis映射文件的包扫描器,配置内容如下:
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.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>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.oak.xiyuyou.mapper" />
</bean>
</beans>
我们配置数据库连接池配置的是Druid连接池,Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。
4)创建mapper包
们可以看到扫描的包是com.oak.xiyuyou.mapper
但是这个包还不存在,下面我们来创建它: