配置文件分四个
spring.xml
springmvc-servlet.xml
spring-mybatis.xml
jdbc.properties
spring.xml配置
<context:component-scan base-package="yb.service.impl"></context:component-scan>
springmvc-servlet.xml
<context:component-scan base-package="yb.controller"></context:component-scan>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/html/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
spring-mybatis.xml
<!-- 加载外部资源文件 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
>
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath:yb/mapping/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="yb.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
jdbc.properties 配置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/testjdbc.username=
jdbc.password=
mybatis的映射文件(yb.mapping.usermapping.xml)
<mapper namespace="yb.dao.UsersMapping" >
<resultMap type="yb.entity.Users" id="userMap">
<id property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="password" column="password"/>
</resultMap>
<select id="findUserById" parameterType="int" resultMap="userMap">
select * from Users where id=#{id}
</select>
</mapper>