SpringBoot + Mybatis 增删改查实例教程详细解读
入门须知
文章概览
实现功能
项目结构
代码实例、代码解读
接口测试
实现功能
用户登录
文章列表
文章详情查询
文章新增
文章修改
文章查看
文章删除
项目结构
结构划分:Controller=>Service=>Dao=>Entity
用戶操作
Controller
package com.sm.service.controller;
import com.sm.service.entity.User;
import com.sm.service.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody
User login(@RequestBody User user) throws Exception {
logger.error("用户登录");
String username = "";
String password = "";
if (user.getUsername() != null) {
username = user.getUsername();
}
if (user.getPassword() != null) {
password = user.getPassword();
}
if (username == null || password == null) {
logger.error("未获取到数据!");
return null;
} else {
User user_rs = userService.findUserByName(username);
if (user_rs != null) {
String pass_rs = user_rs.getPassword();
if (pass_rs.equals(user.getPassword())) {
return user_rs;
} else {
return null;
}
} else {
return null;
}
}
}
}
技术解析:
@RestControlle
@RestController =>相当于Restbody + Controller
标识这个类为控制器 同时返回数据为json 数据 return的数据都变成json的格式,返回到前端,不会跳转界面
@RequestMapping
@RequestMapping 控制路由地址
调用接口 流程:主机: 端口号 / 服务器主访问路径 /Api/
@RequestMapping(value = “/login”, method = RequestMethod.POST)
@RequestMapping 需要使用 method 指定方法类型
RequestMethod取值 POST/GET/PUT/DELETE
也可以使用@PostMapping 省略 方法类型
@AutoWrite
@AutoWrite => get/set 方法
spring可以自动帮你把bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get
@RequestParam
@RequestParam
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
@RequestBody
@RequestBody
处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。
•GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
•POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
功能解析:
流程:userService.findUserByName => 判断用户是否存在=>return User=>根据结果判断请求参数 是否 与 结果相等
Service
package com.sm.service.service;
import com.sm.service.dao.UserDao;
import com.sm.service.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired(required=false)
private UserDao userDao;
public User findUserByName(String name) throws Exception{
return userDao.findUserByName(name);
}
}
Dao
package com.sm.service.dao;
import com.sm.service.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserDao {
@Select("select * from d_user where username = #{username}")
User findUserByName(@Param("username") String name);
}
@Mapper
**您可能已经知道,要在Spring中使用MyBatis,至少需要一个SqlSessionFactory和至少一个mapper接口。
MyBatis-Spring-Boot-Starter将:
自动检测现有数据源
是否将创建并注册一个SqlSessionFactory实例,并使用SqlSessionFactoryBean将该数据源作为输入传递
是否创建并注册一个从SqlSessionFactory中获得的SqlSessionTemplate实例
自动扫描映射器,将它们链接到SqlSessionTemplate,并将它们注册到Spring上下文,以便将它们注入到bean中 **
使用@Mapper注解不需要手动配置mapper.xml
@Select
@Select 搭配 @Mapper 写入需要操作的Sql 语句
Entity
实体类 不做展示
测试
文章操作
Controller
package com.sm.service.controller;
import com.sm.service.entity.Article;
import com.sm.service.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
ArticleService articleService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/*文章分页列表*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public @ResponseBody
PageInfo list_all(@RequestParam(value = "title", required = false) String title, @RequestParam(value = "current_index", required = false)
Integer current_index, @RequestParam(value = "pagesize", required = false) Integer pagesize) throws Exception {
if (null == current_index) current_index = 1;
if (null == pagesize) pagesize = 7;
PageHelper.startPage(current_index, pagesize);
List<Article> page_list = articleService.list(title);
if (null != page_list) {
PageInfo<Article> page_ = new PageInfo<Article>(page_list, 5);
return page_;
} else {
return null;
}
}
/*获取文章详情*/
@RequestMapping(value = "/details/{id}", method = RequestMethod.GET)
public Article details(@PathVariable(name = "id") Integer id) {
Article article = articleService.details(id);
if (null != article) {
logger.info("文章信息" + article);
return article;
} else {
return null;
}
}
/*修改文章信息*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
public Boolean update(@RequestBody Article article) {
Boolean result = articleService.update(article);
if (result) {
return true;
} else {
return false;
}
}
/*新增文章信息*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public Boolean add(@RequestBody Article article) {
Boolean result = articleService.add(article);
if (result) {
return true;
} else {
return false;
}
}
/*删除文章信息*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public Boolean delete(@PathVariable(value = "id") Integer id) {
if (null != id) {
Boolean result = articleService.delete(id);
if (result) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
技术解析:
文章分页列表
@RequestParam
@RequestParam获取 url 地址 参数=>(value = 参数名, required = 是否必须)
默认配置 required 为 false 防止空指针异常
PageHelper 分页插件:
使用步骤:
1:查询方法执行前
PageHelper.startPage(current_index, pagesize);
PageInfo page = new PageInfo(list, 5);
使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行了
PageInfo 数据格式
文章详情
@RequestMapping(value = “/details/{id}”, method = RequestMethod.GET)
将 URL 中占位符参数绑定到控制器处理方法的入参中
通过 PathVariable 获取 URL 地址上参数
@PathVariable(name = URLParamName)
Service
package com.sm.service.service;
import com.sm.service.dao.ArticleDao;
import com.sm.service.entity.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ArticleService {
@Autowired(required = false)
private ArticleDao articleDao;
public List<Article> list(String title) {
return articleDao.list('%' + title + '%');
}
public Article details(Integer id) {
return articleDao.details(id);
}
public Boolean update(Article article) {
try {
articleDao.update(article.getTitle(), article.getD_abstract(), article.getContent(), article.getId());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Boolean add(Article article) {
try {
articleDao.add(article.getTitle(), article.getD_abstract(), article.getContent());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Boolean delete(Integer id) {
try {
articleDao.delete(id);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Dao
package com.sm.service.dao;
import com.sm.service.entity.Article;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ArticleDao {
@Select("select * from d_article where title like #{title} and state=1 order by create_time desc")
@Results(id = "d_article_list_Map", value = {
@Result(column = "abstract", property = "d_abstract"),
})
List<Article> list(@Param("title") String title);
@Select("select * from d_article where id = #{id}")
@Results(id = "d_article_details_Map", value = {
@Result(column = "abstract", property = "d_abstract"),
})
Article details(@Param("id") Integer id);
@Select("update d_article set title=#{title},abstract=#{abstract},content=#{content},update_time=sysdate() where id=#{article_id}")
Boolean update(@Param("title") String title, @Param("abstract") String b_abstract, @Param("content") String content, @Param("article_id") Integer article_id);
@Select("insert into d_article(title,abstract,content) value(#{title},#{abstract},#{content})")
void add(String title, @Param("abstract") String d_abstract, String content);
@Select("update d_article set state=0 where id=#{id}")
Boolean delete(Integer id);
}
代码解析:
@Results 结果映射=>数据库中 abstract java 本地 关键字 => 映射为 d_abstract
@Select 参数传递方式:
方法1:顺序传参法
select * from user
where user_name = #{0} and id= #{1}
User info(String username,Integer id)
Entity
实体类 不做展示
测试
文章列表
文章新增
文章详情
文章修改
文章删除
问题解决:
问:PageHelper 无法分页,返回全部数据?
注意 PageHelp 顺序位置,判断分页参数是否为空
Spring Boot + Mybatis 源码地址
本文地址:https://blog.csdn.net/ForeverBana/article/details/107091660
上一篇: Android日期和时间选择器实现代码
下一篇: C#实现对二维数组排序的方法