首页
绘画广场
知识星球
编程知识
生活知识
AI资讯
办公知识
关于我们
搜索
搜索
首页
编程知识
正文
Spring Boot与MyBatis Plus实现增删改查示例代码
分享者:若云
发布日期: 2024-07-27
浏览量:1073
以下是一个使用Spring Boot和MyBatis Plus实现增删改查的示例代码: 1. 创建一个实体类 `User`,表示用户信息: ```java import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; // 省略构造方法、getter和setter方法 } ``` 2. 创建一个Mapper接口 `UserMapper`,继承自 `BaseMapper` 并指定泛型为 `User`: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper
{ } ``` 3. 创建一个Service接口 `UserService`,定义增删改查的方法: ```java import java.util.List; public interface UserService { User getById(Long id); List
getAll(); void save(User user); void updateById(User user); void deleteById(Long id); } ``` 4. 创建一个Service接口的实现类 `UserServiceImpl`,注入 `UserMapper` 并实现方法: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { private UserMapper userMapper; @Autowired public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; } @Override public User getById(Long id) { return userMapper.selectById(id); } @Override public List
getAll() { return userMapper.selectList(null); } @Override public void save(User user) { userMapper.insert(user); } @Override public void updateById(User user) { userMapper.updateById(user); } @Override public void deleteById(Long id) { userMapper.deleteById(id); } } ``` 5. 创建一个Controller类 `UserController`,注入 `UserService` 并实现增删改查的接口: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { private UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @GetMapping("/{id}") public User getById(@PathVariable Long id) { return userService.getById(id); } @GetMapping("/") public List
getAll() { return userService.getAll(); } @PostMapping("/") public void save(@RequestBody User user) { userService.save(user); } @PutMapping("/{id}") public void updateById(@PathVariable Long id, @RequestBody User user) { user.setId(id); userService.updateById(user); } @DeleteMapping("/{id}") public void deleteById(@PathVariable Long id) { userService.deleteById(id); } } ``` 以上示例中,我们使用了MyBatis Plus提供的基础Mapper `BaseMapper` 来简化数据库操作,利用Spring Boot的依赖注入机制将Mapper注入到Service和Controller中,实现了增删改查的功能。 希望这个示例能够帮助到你。如果还有其他问题,请随时提问。
相关内容
如何使用数据库统计文章访问量
WordPress中使用AJAX获取目标网站标题和描述
常用的cron表达式清单
常用的正则表达式总结
如何在Java中处理文件操作?请提供一个例子来说明如何读取和写入文件。