根本步骤

Step1 搭建我的项目根本框架

创立controller、service、mapper、pojo包构造及相干类文件,如图:

Step2 导入jar包

  1. mysql 驱动jar包
  2. mybatis jar包
  3. spring 外围包
  4. spring整合mybatis jar包
  5. spring-jdbc、spring-aop、spring-tx、spring-web jar包

Step3 编写配置文件

src文件夹下创立applicationcontext.xml文件,进行如下配置:

  1. 配置DataSource bean,采纳属性注入的形式配置连贯数据库的信息
  2. 配置SqlSessionFactory bean,采纳依赖注入的形式将数据源bean配置进去
  3. 配置Mapper包扫描bean,将sqlsessionfactory依赖注入并配置指标扫描包门路
    mapper bean的id默认为Mapper文件名首字母小写
  4. 配置Service bean,依赖注入mapper bean

示例:

<!-- 配置数据源:mybatis联合spring的包 --><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:3306/sxt_mybatis_learning?characterEncoding=utf8"></property>    <property name="username" value="root"></property>    <property name="password" value="root"></property></bean><!--配置SqlSession工厂Bean--><bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref = "datasource"></property></bean><!--配置Mapper包扫描bean--><bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="sqlSessionFactory" ref="factory"></property>    <property name="basePackage" value="com.gcp.mapper"></property></bean><!--配置service bean--><bean id="flowerService" class="com.gcp.service.impl.FlowerServiceImpl">    <property name="flowerMapper" ref="flowerMapper"></property></bean>

Step4 Mapper层

在Mapper编写数据库操作代码

Step5 Service层

  1. 申明Mapper属性,并提供getter、setter办法
  2. 编写service业务代码

Step6 Controller层

  1. 申明Service属性
  2. 在init办法中实现Spring容器内资源的初始化加载,获取业务层对象赋值给service属性
  3. 编写servlet层代码

示例:

@Overridepublic void init() throws ServletException {    ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());    flowerService = (FlowerService) ac.getBean("flowerService");}

Step7 配置我的项目的web.xml文件

  1. 配置Spring环境加载文件的门路参数
  2. 配置监听器

示例:

<context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationcontext.xml</param-value></context-param><listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>