mybatis springboot

MyBatis怎么与SpringBoot快速集成

小亿
82
2024-05-08 13:40:12
栏目: 编程语言

MyBatis与Spring Boot的集成非常简单,只需要在Spring Boot项目中添加MyBatis和相关依赖,然后配置MyBatis的数据源和Mapper扫描即可。

以下是一个简单的步骤:

1、在pom.xml中添加MyBatis和相关依赖:

```xml

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.2.0

org.springframework.boot

spring-boot-starter-jdbc

org.apache.commons

commons-lang3

3.12.0

```

2、配置数据源和MyBatis的Mapper扫描:

在application.properties或application.yml中添加数据库连接配置:

```properties

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_example

spring.datasource.username=root

spring.datasource.password=password

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

```

然后在Spring Boot的启动类上添加`@MapperScan`注解来扫描Mapper接口:

```java

@SpringBootApplication

@MapperScan("com.example.mapper")

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

```

3、创建Mapper接口和对应的Mapper.xml文件:

创建一个Mapper接口,例如UserMapper.java:

```java

@Mapper

public interface UserMapper {

User getUserById(Long id);

}

```

然后在resources目录下创建一个UserMapper.xml文件,定义SQL语句:

```xml

```

4、在Service或Controller中注入Mapper接口并使用:

```java

@Service

public class UserService {

@Autowired

private UserMapper userMapper;

public User getUserById(Long id) {

return userMapper.getUserById(id);

}

}

```

这样就完成了MyBatis与Spring Boot的集成,可以通过Mapper接口来操作数据库。

0
看了该问题的人还看了