SM整合Spring+Mybatis
程序员文章站
2022-07-13 21:19:05
...
相关依赖(jar)
(mybatis-spring.jar spring-tx.jar spring-jdbc.jar spring-expression.jar
spring-context-support.jar spring-core.jar spring-context.jar
spring-beans.jar spring-aop.jar spring-web.jar commons-logging.jar
commons-dbcp.jar ojdbc.jar mybatis.jar log4j.jar commons-pool.jar)
#数据库信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useUnicod=true&characterEncoding=UTF-8
username=root
pwd=123321
(1)创建Mapper映射文件
<!-- namespace:该mapper.xml映射文件的 唯一标识 -->
<mapper namespace="org.qhit.mapper.StudentMapper">
<select id="queryStudentByStuid" parameterType="int"
resultType="org.qhit.bean.Student" >
select * from student where id = #{stuId}
</select>
(2)配置数据源(dbcp)
<!-- 配置数据库相关(dbcp数据源)-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${pwd}"></property>
</bean>
(3)创建Mybatis核心
<!-- 创建Mybatis核心-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<!--获取数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--获取Mapper映射文件-->
<property name="mapperLocations" value="org/qhit/mapper/*.xml"></property>
</bean>
(4)三种整合方式
(1) 第一种方式生成mapper对象
<bean class="org.qhit.dao.impl.StudetnDaoImpl" id="studetnDao">
<!--sqlSessionFactory获取Mybatis配置-->
property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean
(2第二种方式生成mapper对象)
<!--class指定mybatis.spring.mapper.MapperFactoryBean-->
<bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--mapperInterface获取指定Mapper映射文件-->
<property name="mapperInterface" value="org.lanqiao.mapper.StudentMapper"></property>
<!--sqlSessionFactory获取Mybatis配置-->
<property name="sqlSessionFactory" ref="sqlSessionFacotry"></property>
</bean>
(3)第三种方式生成mapper对象(批量产生多个mapper)
批量产生Mapper对在SpringIOC中的 id值 默认就是 首字母小写接口名 (首字母小写的接口名=id值)
<!--class指定org.mybatis.spring.mapper.MapperScannerConfigurer-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mappers">
<!--mapperInterface获取指定Mapper映射文件-->
<property name="mapperInterface" value="org.qhit.mapper.StudentMapper"></property>
<!--sqlSessionFactory获取Mybatis配置-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!--basePackage需要扫描的包多个,分隔-->
<property name="basePackage" value="org.qhit.mapper"></property>
</bean>