温馨提示×

springboot如何整合mybatis

小亿
119
2024-01-17 03:54:58
栏目: 编程语言

要将Spring Boot与MyBatis整合,可以按照以下步骤操作:

步骤1:在pom.xml文件中添加MyBatis和MyBatis-Spring-Boot-Starter依赖。

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> 

步骤2:配置数据库连接信息和MyBatis属性。

在application.properties或application.yml文件中添加以下配置:

spring.datasource.url=jdbc:mysql://localhost:3306/db_example spring.datasource.username=db_username spring.datasource.password=db_password mybatis.mapper-locations=classpath*:mapper/*.xml 

步骤3:创建MyBatis的Mapper接口和对应的XML文件。

创建一个Mapper接口,例如UserMapper.java,并编写Mapper方法。

import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface UserMapper { @Select("select * from users") List<User> getAllUsers(); } 

在resources/mapper目录下创建UserMapper.xml文件,配置SQL语句。

<mapper namespace="com.example.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.entity.User"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="email" property="email" /> </resultMap> <select id="getAllUsers" resultMap="BaseResultMap"> select * from users </select> </mapper> 

步骤4:创建Service和Controller。

创建一个UserService接口和UserServiceImpl实现类。

public interface UserService { List<User> getAllUsers(); } @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; public List<User> getAllUsers() { return userMapper.getAllUsers(); } } @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public List<User> getAllUsers() { return userService.getAllUsers(); } } 

以上就是整合Spring Boot和MyBatis的基本步骤。在Spring Boot启动时,MyBatis会自动根据配置文件和注解扫描Mapper接口,并生成代理实现类。可以使用这些Mapper接口来访问数据库。

0