这里记录一下自己学习mybatis-spring的集成配置,如有错误,希望大家拍砖。
程序目录结构
1mybatis-config.xml的配置,这里只有基本配置,其它的在Beans.xml里面配置。
<?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> <settings> <!--log4j2 mybatis配置--> <setting name="logImpl" value="LOG4J2"/> </settings> <!--定义mapper里的别名--> <typeAliases> <!--直接定义一个包名--> <package name="com.zns.model"/> <!--一个实体类对应一个别名--> <!--<typeAlias type="com.zns.model.Admin" alias="Admin"/>--> </typeAliases> </configuration>
我这里typeAliases只接定义了一个包,这样就不用没一个实体类都去定义了。
2Spring的Beans.xml配置
<?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:context="http://www.springframework.org/schema/context"
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.xsd">
<!--导入jdbc配置文件-->
<context:property-placeholder location="classpath*:jdbc.properties"/>
<!--配置spring数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!--mybatis spring 事务管理-->
<!--mybatis-spring手册上是这样配置的,不知道还有没有其它的配置方式-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--导入mybatis-config配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--导入mapper xml-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--配置sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--扫描所有映射器(mapper接口类)-->
<!--在使用单个映身器的时候用@Autowired注解就可以了,不需要其它配置-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zns.mapper"/>
</bean>
<!--注册映射器-->
<!--<bean id="adminMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!--<property name="mapperInterface" value="com.zns.mapper.AdminMapper"/>-->
<!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>-->
<!--</bean>-->
<bean id="adminService" class="com.zns.service.AdminService"/>
</beans>Spring的数据源(dataSource)还有其它的几种,如:dbcp或者是c3p0等。大家可以自己google一下。
这里的配置是spring-mybatis的配置,还没有放到web环境里。
大牛不要喷啊。菜鸟学习。
本文出自 “PHP学习” 博客,请务必保留此出处http://xtceetg.blog.51cto.com/5086648/1906301
原文地址:http://xtceetg.blog.51cto.com/5086648/1906301