controller
package com.example.demo07.controller;
import com.example.demo07.dto.Book;
import com.example.demo07.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
IBookService bookService;
@GetMapping
public List<Book> getAll(){
//该方法继承自IService
return bookService.list();
}
@PostMapping
//@RequestBody 接收的是请求体里面的数据(post方式参数在请求体中),@RequestBody以简单对象接收前端传过来的json数据
public Boolean save(@RequestBody Book book){
//该方法继承自IService
return bookService.save(book);
}
@PutMapping
public Boolean update(@RequestBody Book book){
//该方法继承自IService
return bookService.updateById(book);
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id){
//该方法继承自IService
return bookService.removeById(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id){
//该方法继承自IService
return bookService.getById(id);
}
}
测试
getAll
结果
[
{
"id": 1,
"type": null,
"name": "毛选",
"description": null
},
{
"id": 2,
"type": "哲学",
"name": "局外人",
"description": null
},
{
"id": 3,
"type": "文学",
"name": "葡萄牙的高山",
"description": "苦难"
},
{
"id": 4,
"type": "文学",
"name": "活着",
"description": "苦难"
},
{
"id": 5,
"type": "文学",
"name": "平凡的世界",
"description": null
},
{
"id": 6,
"type": "文学",
"name": "孩子王",
"description": null
}
]
测试
save
发送json格式参数
结果
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@17d8f5bd] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@77a5fa56] will not be managed by Spring
==> Preparing: INSERT INTO book ( type, name ) VALUES ( ?, ? )
==> Parameters: 文学(String), 美丽新世界(String)
<== Updates: 1
测试
update
结果
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@705b84a9] will not be managed by Spring
==> Preparing: UPDATE book SET type=?, name=? WHERE id=?
==> Parameters: 文学(String), 孔乙己(String), 7(Integer)
<== Updates: 1