返回

MyBatis与Spring Boot集成实战

后端




在Spring Boot中,我们可以轻松地将MyBatis集成到项目中,并进行数据库操作。MyBatis是一个优秀的ORM框架,它可以帮助我们简化数据库操作,提高开发效率。

1. 添加依赖

首先,我们需要在pom.xml文件中添加MyBatis和Spring Boot对MyBatis的支持依赖:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
</dependencies>

2. 配置数据源

接下来,我们需要在application.properties文件中配置数据源:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

3. 配置MyBatis

然后,我们需要在application.properties文件中配置MyBatis:

mybatis.mapper-locations=classpath:mapper/*.xml

4. 创建Mapper接口

接下来,我们需要创建Mapper接口,以便于我们操作数据库。例如,我们可以创建一个UserMapper接口:

@Mapper
public interface UserMapper {

    @Select("select * from user where id = #{id}")
    User selectById(Integer id);

    @Insert("insert into user (name, age) values (#{name}, #{age})")
    int insert(User user);

    @Update("update user set name = #{name}, age = #{age} where id = #{id}")
    int update(User user);

    @Delete("delete from user where id = #{id}")
    int delete(Integer id);

}

5. 使用MyBatis

最后,我们就可以在代码中使用MyBatis了。例如,我们可以使用UserMapper接口来查询用户:

@Autowired
private UserMapper userMapper;

@GetMapping("/user/{id}")
public User getUser(@PathVariable Integer id) {
    return userMapper.selectById(id);
}

总结

通过以上步骤,我们就完成了MyBatis与Spring Boot的集成,并可以进行数据库操作了。MyBatis是一个功能强大且易于使用的ORM框架,它可以帮助我们简化数据库操作,提高开发效率。