SpringBoot-mysql(刪改查)
阿新 • • 發佈:2020-11-12
- controller
package com.Lee.connect.controller; import com.Lee.connect.mapper.UserMapper; import com.Lee.connect.table.TableUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(value = "/") public class UserController{ @Autowired UserMapper userMapper; @RequestMapping(value = "/getUser") @ResponseBody public Object getUser(@RequestParam("id") Integer id){ TableUser user = userMapper.getUserById(id); return user; } @RequestMapping(value = "/delUser") @ResponseBody public Object delUser(@RequestParam("id") Integer id){ userMapper.delUserById(id); return "delete finished"; } @RequestMapping(value = "/setUser") @ResponseBody public Object setUser(@RequestParam("UserName") String UserName,@RequestParam("PassWord") String PassWord,@RequestParam("id") Integer id){ TableUser user = new TableUser(); user.setId(id); user.setUserName(UserName); user.setPassWord(PassWord); userMapper.updateUser(user); return user; } }
此處定義了三個方法,分別用於刪改查
@RequesBody的value值也根據方法的作用進行更改,在http中就是請求的路徑不同
使用@RequestParam("username") String username可以作為類的引數,這樣就需要使用?引數1&引數2來http請求傳入引數給controller
- mapper
package com.Lee.connect.mapper; import com.Lee.connect.table.TableUser; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Component; @Mapper @Component(value = "UserMapper") public interface UserMapper { //select @Select("select * from t1 where id=#{id}") TableUser getUserById(@Param("id") Integer id); //delete @Delete("delete from t1 where id=#{id}") void delUserById(@Param("id") Integer id); //update @Update("update t1 set UserName=#{UserName},PassWord=#{PassWord} where id=#{id}") void updateUser(TableUser user); }
此介面定義了三個方法,分別使用了不同的sql語句
注意查會返回一個物件,使用entity對應的tableuser進行接收
刪和改則無返回值,使用void
- 傳參
使用/value?引數1&引數2在位址列中新增引數
/value為controller中使用的方法
引數為@RequestParam("username") String username中對應的引數