您的位置:首页 > 编程语言 > Java开发

spring整合mybatis总结

2017-10-29 14:39 274 查看
由于原生态的JDBC编程存在硬编码问题,维护不方便于是mybatis等持久层框架应运而生。
mybatis开发dao层有两种方法
(1)开发dao接口及其实现类
(2)mapper代理开发。它是对(1)的优化与发展。
下面只介绍mapper代理开发。先剖析一下原理。
mapper的代理实现类是由org.mybatis.spring.mapper.MapperScannerConfigurer生成的,并且依赖于org.mybatis.spring.SqlSessionFactoryBean对象。
而sqlSessionFactory对象又依赖“数据源”和“mybatis配置文件(或者是XXXmapper.xml的路径)”。
所以我们只需要配置好“数据源”、“sqlSessionFactory”、“或者是XXXmapper.xml的路径”三处即可,当然也需要遵循mapper代理开发的一些规范。


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:config/db.properties" />

<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc_driverClassName}" />
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>

<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件
(这是另一种配置方式,采用此方式可在mybatis配置文件中配置更多东西)
properties(属性)
settings(全局配置参数)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境集合属性对象)
environment(环境子属性对象)
transactionManager(事务管理)
dataSource(数据源)
mappers(映射器)
)
<property name="configLocation" value="config/SqlMapConfig.xml" />
-->
<property name="mapperLocations" value="classpath:cn/tqs/easyui/mapper/*.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.tqs.easyui.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息