步骤
-
引入mybatis
1.1 引入mybatis主配置文件:mybatis-config.xml
1.2编写mapper接口,编写方法及注解
1.3编写service()
1.4编写service对象测试方法
-
引入spring
2.1编写主配置文件:application-context.xml
2.2在测试类中测试spring是否引用成功:编写一个bean,利用applicationContext.getBean(xxx.class)获取实例测试
-
开始整合mybatis-spring
3.1 利用spring创建mybatis需要的dataSource。spring为mybatis提供一个类,可以专门用来连接数据库,spring-jdbc.dataSource:负责连接、管理数据库
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3308/mybatis?useUnicode=true&characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> 复制代码
3.2 配置factory:
mybatis为mybatis与spring整合时提供了一个工具类,用来创建factory,在mybatis-spring包中
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置dataSource:连接到数据库 --> <property name="dataSource" ref="dataSource"></property> </bean> 复制代码
3.3 开启扫描,作用类似于mybatis-config.xml mappers->package。mybatis-spring 为整合时提供了一个类, 可以用来扫描mybatis的mapper,这个类:可以帮程序员自动生成session及mapper对象,就不需要程序员手动的创建
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定扫描的包 --> <property name="basePackage" value="com.dyr.mapper"></property> <!-- 配置工厂 --> <property name="sqlSessionFactory" ref="factory"></property> </bean> 复制代码
3.4 配置service
<bean id="studentService" class="com.dyr.service.StudentService">
<!-- 第3步扫描自动生成StudentMapper -->
<property name="mapper" ref="studentMapper"></property>
</bean>
复制代码
3.5 事务配置:待续...
3.6引入action
<bean id="studentAction" class="com.dyr.action.StudentAction" scope="prototype">
<property name="service" ref="studentService"></property>
</bean>
复制代码
3.7 在web.xml引入spring核心库