和只使用mybatis一样,依然先写好:
实体类Book.java,dao接口BookDAO.java,映射文件BookMapper.xml
然后不用写mybatis的xml配置文件,直接写在spring的xml配置文件中,当作spring中的bean。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!--1 引入属性文件,在配置中占位使用 -->
<context:property-placeholder location="classpath:db.properties" />
<!--2 配置C3P0数据源 -->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--驱动类名 -->
<property name="driverClass" value="${jdbc.driver}" />
<!-- url -->
<property name="jdbcUrl" value="${jdbc.url}" />
<!-- 用户名 -->
<property name="user" value="${jdbc.username}" />
<!-- 密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
<property name="acquireIncrement" value="5"></property>
<!-- 初始连接池大小 -->
<property name="initialPoolSize" value="10"></property>
<!-- 连接池中连接最小个数 -->
<property name="minPoolSize" value="5"></property>
<!-- 连接池中连接最大个数 -->
<property name="maxPoolSize" value="20"></property>
</bean>
<!--3 会话工厂bean sqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 传入 数据源 -->
<property name="dataSource" ref="datasource"></property>
<!-- 传入 entity类所在包 -->
<property name="typeAliasesPackage" value="com.cm.entity"></property>
<!-- 传入 mapper.xml映射文件所在路径 -->
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"></property>
</bean>
<!--4 自动扫描对象关系映射 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 传入 sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 传入 dao接口所在包 -->
<property name="basePackage" value="com.cm.dao"></property>
</bean>
<!-- 1,2,3,4共同实现了mybatis-config.xml的功能 -->
<!--5 声明式事务管理 -->
<!--定义事务管理器,由spring管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 传入 数据源 -->
<property name="dataSource" ref="datasource"></property>
</bean>
<!--支持注解驱动的事务管理,指定事务管理器 -->
<!-- 传入 5声明的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--6 容器自动扫描IOC组件 -->
<!-- 通过@Component自动发现并注册bean -->
<context:component-scan base-package="com.cm"></context:component-scan>
</beans>