Spring与Mybatis整合详解

上传:smqysmqygo 浏览: 13 推荐: 0 文件:zip 大小:13.75KB 上传时间:2023-03-09 00:58:13 版权申诉

Spring与Mybatis整合详解

Spring与Mybatis是一种非常流行的Java开发框架组合,它们可以很好地协同工作,帮助开发人员更高效地开发Web应用程序。

在这篇文章中,我们将探讨Spring与Mybatis的整合方式,并介绍如何使用它们来构建一个基本的Web应用程序。

整合步骤

第一步:添加依赖

在pom.xml文件中添加Spring和Mybatis的依赖:

<dependency>
    <groupid>org.springframeworkgroupid>
    <artifactid>spring-contextartifactid>
    <version>5.1.4.RELEASEversion>
dependency>

<dependency>
    <groupid>org.mybatisgroupid>
    <artifactid>mybatisartifactid>
    <version>3.5.0version>
dependency>

<dependency>
    <groupid>org.mybatisgroupid>
    <artifactid>mybatis-springartifactid>
    <version>2.0.2version>
dependency>

第二步:配置Spring和Mybatis

在Spring配置文件中添加Mybatis的配置:

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">property>
    <property name="url" value="jdbc:mysql://localhost:3306/test">property>
    <property name="username" value="root">property>
    <property name="password" value="root">property>
bean>

<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
    <property name="dataSource" ref="dataSource">property>
    <property name="mapperLocations" value="classpath*:mapper/*.xml">property>
bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.mapper">property>
bean>

第三步:编写Mapper接口和SQL语句

编写Mybatis的Mapper接口和SQL语句:

public interface UserMapper {
    @Select("select * from user where id = #{id}")
    User findById(int id);
}

第四步:编写Service和Controller

编写Service和Controller:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(int id) {
        return userMapper.findById(id);
    }
}

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/{id}")
    public User findById(@PathVariable int id) {
        return userService.findById(id);
    }
}

第五步:运行应用程序

启动应用程序并访问http://localhost:8080/user/1,应该能够看到用户信息。

总结

在本文中,我们介绍了Spring与Mybatis的整合方式,并演示了如何使用它们来构建一个基本的Web应用程序。希望这篇文章能够帮助您更好地了解Spring与Mybatis的整合。

上传资源
用户评论