MyBatis怎么与Spring框架集成使用

2024-05-08,

要将MyBatis与Spring框架集成使用,可以按照以下步骤进行操作:

  1. 添加MyBatis和Spring框架的依赖:
    在Maven或Gradle的配置文件中添加MyBatis和Spring的相关依赖,例如:

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.0</version>
    </dependency>
    
    <!-- MyBatis Spring Boot Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.9</version>
    </dependency>
    
  2. 配置MyBatis数据源和SqlSessionFactory:
    在Spring的配置文件中配置数据源和SqlSessionFactory,例如:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc//localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
  3. 配置MyBatis的Mapper扫描:
    在Spring的配置文件中配置Mapper的扫描路径,例如:

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper"/>
    </bean>
    
  4. 编写Mapper接口和Mapper映射文件:
    编写Mapper接口和对应的Mapper映射文件,例如:

    public interface UserMapper {
        User getUserById(Long id);
    }
    
    <mapper namespace="com.example.mapper.UserMapper">
        <select id="getUserById" resultType="com.example.model.User">
            SELECT * FROM user WHERE id = #{id}
        </select>
    </mapper>
    
  5. 在Service或Controller中注入Mapper接口并调用方法:
    在Service或Controller中注入Mapper接口,并调用方法进行数据库操作,例如:

    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }
    

通过以上步骤,就可以将MyBatis与Spring框架集成使用,实现数据访问操作。

《MyBatis怎么与Spring框架集成使用.doc》

下载本文的Word格式文档,以方便收藏与打印。