写出基于spring cloud和mybatis plus,mysql的crud代码
时间: 2024-03-07 20:50:39 浏览: 129
好的,下面是一个简单的基于Spring Cloud和Mybatis Plus的CRUD代码示例,使用MySQL作为数据库:
1. 首先,需要在pom.xml文件中添加相应的依赖:
```
<dependencies>
<!--Spring Cloud相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--Mybatis Plus相关依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
2. 在application.yml文件中配置数据库连接信息和Mybatis Plus相关配置:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.example.demo.entity
```
3. 创建实体类User.java:
```
public class User {
private Long id;
private String name;
private Integer age;
//省略getter/setter方法
}
```
4. 创建Mapper接口UserMapper.java:
```
public interface UserMapper extends BaseMapper<User> {
}
```
5. 创建Service接口和实现类UserService.java:
```
public interface UserService {
boolean save(User user);
boolean deleteById(Long id);
boolean updateById(User user);
User getById(Long id);
List<User> getAll();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public boolean save(User user) {
return userMapper.insert(user) > 0;
}
@Override
public boolean deleteById(Long id) {
return userMapper.deleteById(id) > 0;
}
@Override
public boolean updateById(User user) {
return userMapper.updateById(user) > 0;
}
@Override
public User getById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> getAll() {
return userMapper.selectList(null);
}
}
```
6. 创建Controller类UserController.java:
```
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@GetMapping("/all")
public List<User> getAll() {
return userService.getAll();
}
@PostMapping("/")
public boolean save(@RequestBody User user) {
return userService.save(user);
}
@DeleteMapping("/{id}")
public boolean deleteById(@PathVariable Long id) {
return userService.deleteById(id);
}
@PutMapping("/")
public boolean updateById(@RequestBody User user) {
return userService.updateById(user);
}
}
```
至此,一个简单的基于Spring Cloud和Mybatis Plus的CRUD示例就完成了。需要注意的是,这只是一个简单的示例,实际项目中还需要进行更多的配置和优化。
阅读全文