springboot 整合 mybatis plus
时间: 2023-11-21 10:56:21 浏览: 92
springboot整合mybatis
5星 · 资源好评率100%
以下是Spring Boot整合MyBatis Plus的步骤:
1.在pom.xml文件中添加MyBatis Plus的起步依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
```
2.在application.properties或application.yml文件中配置数据源信息:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
3.创建实体类和Mapper接口,使用MyBatis Plus提供的注解来简化开发:
```java
// 实体类
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
}
// Mapper接口
public interface UserMapper extends BaseMapper<User> {
}
```
4.在启动类上添加@MapperScan注解,扫描Mapper接口:
```java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
5.使用MyBatis Plus提供的方法进行CRUD操作:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> getUserList() {
return userMapper.selectList(null);
}
@Override
public int addUser(User user) {
return userMapper.insert(user);
}
@Override
public int updateUser(User user) {
return userMapper.updateById(user);
}
@Override
public int deleteUser(Long id) {
return userMapper.deleteById(id);
}
}
```
阅读全文