springboot使用java编码配置mybatis
时间: 2024-06-21 11:03:07 浏览: 101
springboot 集成mybatis
Spring Boot是一个流行的Java框架,它简化了微服务的开发流程。MyBatis是一个优秀的持久层框架,用于将Java对象映射到数据库。在Spring Boot中集成MyBatis,你可以快速地管理数据访问和持久化。以下是使用Java配置Spring Boot和MyBatis的基本步骤:
1. 添加依赖:在你的`pom.xml`或`build.gradle`文件中添加Spring Boot的Web和MyBatis的依赖。
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- Gradle (Kotlin) -->
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter")
```
2. 配置数据源(如果你使用JPA,这一步通常是默认的):
```java
@Bean
public DataSource dataSource() {
// 使用HikariCP、Druid或其他数据源配置
return new HikariDataSource();
}
```
3. 配置MyBatis:
```java
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
return factoryBean.getObject();
}
```
4. 定义Mapper接口:
```java
public interface UserMapper {
List<User> getUsers();
}
```
5. 创建Mapper XML映射文件:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="getUsers" resultType="com.example.demo.model.User">
SELECT * FROM users;
</select>
</mapper>
```
6. 注册Mapper:
```java
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Autowired
private UserMapper userMapper;
public List<User> getUsers() {
return userMapper.getUsers();
}
```
阅读全文