Spring整合配置Mybatis:使用Spring 整合 mybatis 的一些全局配置,可以减少开发量,同时约定大于配置也是目前开发的趋势。
mybatis 是一种ORM框架,可以将数据库表与java entity实体类映射起来。
为了减少开发工作量,使用spring-mybatis管理数据库以及mybatis的一些配置属性
一些jdbc基本属性,如jdbc驱动,jdbc登录的用户名,密码等
<property name="jdbcUrl" value="${url}"> <property name="user" value="${username}"> <property name="password" value="${password}"></property></property></property> 数据库连接池的私有属性,如最大连接池数目,事务自动提交,失败重连重试次数等 <!--c3p0私有属性--> <property name="maxPoolSize" value="30"> <property name="minPoolSize" value="10"> <!--关闭连接后不自动commit--> <property name="autoCommitOnClose" value="false"> <!--获取连接超时时间--> <property name="checkoutTimeout" value="1000"> <!--当获取连接失败重试次数--> <property name="acquireRetryAttempts" value="2"></property></property></property></property></property> 配置扫描的对象,如实体类以及mapper对象 ``<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"> <!--配置mybatis全局配置文件:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"> <!--扫描entity包,使用别名,多个用;隔开--> <property name="typeAliasesPackage" value="com.test.entity"> <!--扫描sql配置文件:mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"> </property></property></property></property></bean> 使用Mybatis 一种常用的做法是Dao接口不具体写实现类,而是用mapper和dao接口映射,由spring负责加载dao的实现类,所以要配置具体的dao坐标,以供mybatis扫描。 <!--配置扫描Dao接口包,动态实现DAO接口,注入到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入SqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"> <!-- 给出需要扫描的Dao接口--> <property name="basePackage" value="com.test.dao"> </property></property></bean>