mybatis springboot Example
时间: 2023-08-26 15:05:15 浏览: 105
Sure! Here's an example of using MyBatis with Spring Boot:
First, make sure you have the necessary dependencies in your `pom.xml` file:
```xml
<dependencies>
<!-- other dependencies -->
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
Next, configure the database connection in `application.properties`:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=secret
```
Create a data access object (DAO) interface, for example, `UserMapper.java`:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<User> getAllUsers();
// other CRUD methods...
}
```
Create a model class, for example, `User.java`:
```java
public class User {
private Long id;
private String name;
private String email;
// getters and setters...
}
```
Finally, use the DAO in your service or controller, for example, `UserService.java`:
```java
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
// other service methods...
}
```
That's it! You can now use MyBatis to interact with your database in a Spring Boot application. Remember to annotate your main class with `@MapperScan` to scan the mapper interfaces, and use the `@Autowired` annotation to inject the service or mapper beans where needed.
Hope this helps! Let me know if you have any more questions.
阅读全文