使用Spring 简化MyBatis

1、导入mybatis所有的jar 和 spring 基本包,spring-jdbc,spring-tx,spring-aop,spring整合mybatis的包等。

2、编写spring配置文件applicationCotext.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!-- 数据源封装类,数据源 获取数据连接 spring.jdbc.jar中-->
        <bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
            <property name="username" value="root"></property>
            <property name="password" value="362222"></property>
        </bean>
        <!-- 创建SqlSessionFactory对象 -->
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 数据库连接对象信息来源于dataSouce(上面) -->
            <property name="dataSource" ref="dataSouce"></property>
        </bean>
        <!-- 扫描器相当于mybatis.xml中的mappers下的package标签 ,扫描com.bjsxt.mapper包后会给对应的接口创建对象-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 要扫描那个包 -->
            <property name="basePackage" value="com.bjsxt.mapper"></property>
            <!-- 和factory产生关系 -->
            <property name="sqlSessionFactory" ref="factory"></property>
        </bean>
        <!-- 由spring管理service实现类 -->
        <bean id="airportservice" class="com.bjsxt.service.impl.AirportServiceImpl">
            <property name="airportMapper" ref="airportMapper"></property>
        </bean>
  </beans>

3、编写代码

  3.1 正常编写pojo

  3.2 编写mapper包下时必须使用接口绑定方案或注解方案(必须有接口)

  3.3 正常编写Service接口和Service实现类

    3.3.1 需要在Service实现类中声明Mapper接口对象,并生成get/set方法

  3.4 spring无法管理Servlet

猜你喜欢

转载自www.cnblogs.com/axu521/p/10132701.html