美文网首页JAVA开发实习生日志
Springboot + mysql + jdbc + 增删改查

Springboot + mysql + jdbc + 增删改查

作者: 小丑皇_0624 | 来源:发表于2021-07-27 10:55 被阅读0次

我的增删改查制作过程:

https://www.jianshu.com/p/4820e5f7729c

师傅要求删的时候postman上要用delete方法;改的时候用body,而不用param,用post方法;增的时候也是用body,用post方法。


主要内容

按id查用户

//按照id查询用户信息

@GetMapping(path="/byId")

public@ResponseBody

//请求参数id映射绑定函数参数id,函数参数与数据库参数已在实体通过注解映射绑定

StringgetUserById(@RequestParam("id")Integerid) {

// This returns a JSON or XML with the users

User=userRepository.getUserById(id);

if(User!=null) {

return"{\nid:"+userRepository.findById(id).get().getId()+";\nname:"+userRepository.findById(id).get().getName()+";\nemail:"+userRepository.findById(id).get().getName()+"\n}";

           }

else

return"Your id is wrong.Please dial again!";

   }

@PostMapping(path="/add")// Map ONLY POST Requests

public@ResponseBodyStringaddNewUser(@RequestBodyUsernewUser) {

// @ResponseBody means the returned String is the response, not a view name

// @RequestParam means it is a parameter from the GET or POST request

userRepository.save(newUser);

return"Saved";

}

//按照id删除用户

@DeleteMapping(path="/deleteById")

public@ResponseBody

StringdelUser(@RequestParam("id")Integerid) {

User=userRepository.getUserById(id);

if(User!=null) {

userRepository.deleteById(id);

return"deleted";

   }

else

return"error";

}

//通过id对name字段进行更新

@PutMapping(path="/update")

public@ResponseBody

Stringupdate(@RequestBodyUsernewUser) {

//if(id == User.getId();

if(newUser!=null){

userRepository.save(newUser);

return"Updated";

   }

else{

return"error";

   }

}

@RequestBody后面跟类,不想@RequestParam后面跟数据类型

前者在poatman中用Body写json文件,后者在param中key-value中分别写数据名和内容。

userRepository.save(newUser);

save时不仅保存,还会更新。

查所有用户

@GetMapping(path="/all")

public@ResponseBodyIterable<User>getAllUsers() {

// This returns a JSON or XML with the users

returnuserRepository.findAll();

}

实现这些的话,只需要动controller层,不用管service业务层和其实现层。

师傅检查完后,要我在此基础上能实现文件在服务器上的上传和下载。

于是,我从官网上找了个待完成品。

https://spring.io/guides/gs/uploading-files/

其中许多storage中的properties和exception类需要下官网上的包。

这坑了我好久。

这里还有个网站,写了些关于官网各个主要类的注意点

https://blog.csdn.net/qq_38874492/article/details/105732293


今日小tips:

报错:

    spring-boot-maven-plugin:2.5.2:repackage failed: Unable to find main class

改正:

有俩个main启动,删掉一个。

相关文章

网友评论

    本文标题:Springboot + mysql + jdbc + 增删改查

    本文链接:https://www.haomeiwen.com/subject/ndzgmltx.html