SpringBoot实现增删改查
查询(Get):controller:@RequestMapping("/user")public class UserController {@Autowiredprivate UserMapper userMapper;@GetMappingpublic List<User> index(){List<User> all = userMapper.findAll();r
查询(Get):
controller:
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping
public List<User> index(){
List<User> all = userMapper.findAll();
return all;
}
}
mapper:
@Select("SELECT * from sys_user")
List<User> findAll();
@RequestMapping拼接上@GetMapping的接口才是实际的url
新增(Post):
controller:
@RequestBody:将前台传输的json数据映射转换成java对象
@PostMapping
public Integer save(@RequestBody User user){
return userMapper.insert(user);
}
mapper:
@Insert("Insert into sys_user(username,`password`,nickname,email,phone,address) VALUES (#{username},#{password},#{nickname},#{email},#{phone},#{address})")
int insert(User user);
#{数据} :动态存放数据
请求后台接口测试——使用Postman:
JSON的key和value都是字符串,因此需要使用""(双引号)包裹数据
返回1代表有一条数据被修改了
回到数据库查看到数据成功录入:
修改(Post):
新增和修改都用到save接口,那如何在一个save接口中既做到新增,有做到更新呢?此时就要使用到Service
@Service
public class UserService {
}
@Service:将Service类注入到SpringBoot容器中,让类能够被使用 。因为Service包含component
@Componet:将类注入到SpringBoot容器。
mapper:
@Update("update sys_user set username = #{username},password=#{password},nickname=#{nickname},email=#{email},phone=#{phone},address=#{address} where id = #{id}")
int update(User user);
service:
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int save(User user){
if (user.getId() == null){//user没有id,表示是新增
return userMapper.insert(user);
}else {//否则为更新
return userMapper.update(user);
}
}
}
controller:
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
@PostMapping
public Integer save(@RequestBody User user){
//新增或者更新
return userService.save(user);
}
在postman中测试一下:
在数据库中查看一下:
id=5的数据应该被修改了
动态SQL:
想要单独修改某一行数据,而不影响其他数据,可以使用动态SQL
在resource文件夹中添加mapper文件夹,注意在配置文件中写sql和在mapper接口中使用注解两者不能同时使用,只能二选一。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springboot.mapper.UserMapper">
<update id="update">
update sys_user
<set>
<if test="username !=null">
username = #{username},
</if>
<!--<if test="password !=null">
password = #{password},
</if>-->
<if test="nickname !=null">
nickname = #{nickname},
</if>
<if test="email !=null">
email = #{email},
</if>
<if test="phone !=null">
phone = #{phone},
</if>
<if test="address !=null">
address = #{address}
</if>
</set>
<where>
id = #{id}
</where>
</update>
</mapper>
测试一下:
报错了,
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.springboot.mapper.UserMapper.update
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:235) ~[mybatis-3.5.9.jar:3.5.9]
at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:53) ~[mybatis-3.5.9.jar:3.5.9]
at org.apache.ibatis.binding.MapperProxy.lambda$cachedInvoker$0(MapperProxy.java:108) ~[mybatis-3.5.9.jar:3.5.9]
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660) ~[na:1.8.0_312]
at org.apache.ibatis.util.MapUtil.computeIfAbsent(MapUtil.java:35) ~[mybatis-3.5.9.jar:3.5.9]
at org.apache.ibatis.binding.MapperProxy.cachedInvoker(MapperProxy.java:95) ~[mybatis-3.5.9.jar:3.5.9]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:86) ~[mybatis-3.5.9.jar:3.5.9]
at com.sun.proxy.$Proxy61.update(Unknown Source) ~[na:na]
at com.example.springboot.service.UserService.save(UserService.java:18) ~[classes/:na]
at com.example.springboot.controller.UserController.save(UserController.java:24) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_312]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_312]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_312]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_312]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.17.jar:5.3.17]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.17.jar:5.3.17]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.17.jar:5.3.17]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.60.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.17.jar:5.3.17]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.60.jar:4
显示是找不到UserMapper的update方法。错误原因是,SpringBoot框架找不到mapper文件夹中的User.xml。
解决方法:在配置文件application.yml中给MyBatis配置。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/yaya?serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml #扫描所有MyBatis的xml文件
测试一下:
修改成功!
删除(Delete):
mapper:
@Delete("delete from sys_user where id = #{id}")
Integer deleteById(@Param("id") Integer id);
controller:
// 根据id删除数据
@DeleteMapping("/{id}")
public Integer delete(@PathVariable Integer id){
return userMapper.deleteById(id);
}
@PathVariable:截取前端url的值
测试一下:
id为4的数据被删除了
结语:坚定目标,日日精进,必有所成。共勉! !
更多推荐
所有评论(0)