springboot和mybatisplus详细整合
时间: 2023-11-21 21:57:37 浏览: 89
SpringBoot和MybatisPlus的整合可以让我们更加方便地进行数据库操作,以下是详细的整合步骤:
1.在pom.xml文件中添加MybatisPlus和Clickhouse的依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>ru.yandex.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>0.3.1</version>
</dependency>
```
2.在application.properties文件中添加Clickhouse的配置:
```properties
spring.datasource.driver-class-name=ru.yandex.clickhouse.ClickHouseDriver
spring.datasource.url=jdbc:clickhouse://localhost:8123/default
spring.datasource.username=default
spring.datasource.password=
```
3.创建实体类和Mapper接口,使用MybatisPlus的注解来简化代码:
```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.在Service中注入Mapper,并使用MybatisPlus提供的方法进行数据库操作:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> listUsers() {
return userMapper.selectList(null);
}
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
@Override
public void saveUser(User user) {
userMapper.insert(user);
}
@Override
public void updateUser(User user) {
userMapper.updateById(user);
}
@Override
public void deleteUser(Long id) {
userMapper.deleteById(id);
}
}
```
5.在Controller中注入Service,并编写接口方法:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> listUsers() {
return userService.listUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("")
public void saveUser(@RequestBody User user) {
userService.saveUser(user);
}
@PutMapping("")
public void updateUser(@RequestBody User user) {
userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
```
阅读全文