Create project
spring web, mybatis, mysql check
Join mp and druid, and see the basic understanding of SpringBoot for dependencies – Programmer Sought
yml data source
server: port: 81 spring: datasource: druid: #integration mode configuration driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/jdbc username: root password: root123
Write a data table and write a domain package entity class.
@Data @NoArgsConstructor @AllArgsConstructor public class Book { private Integer id; private String name; private String price ;//decimal }
Write a mappr package interface @Mapper to generate an implementation class and inherit mp
@Mapper public interface BookMapper extends BaseMapper<Book> { }
New error
//The id generated by mybatis-plus by default is the self-defined snowflake algorithm
//The id auto-increment method provided by the database The way to configure id auto-increment in yml: set to auto auto-increment: id-type:auto
mybatis-plus: global-config: db-config: id-type: auto
test case
@SpringBootTest class SpringbootBeginQuickstartApplicationTests { @Autowired private BookMapper bookMapper; @Test void contextLoads() { System.out.println(bookMapper.selectById(1)); System.out.println(bookMapper.insert(new Book(null,"ddd","12"))); System.out.println(bookMapper.updateById(new Book(1,"update","12")));//return value success 1, failure 0 System.out.println(bookMapper.deleteById(1)); //Success 1, failure 0 System.out.println(bookMapper.selectList(null)); //The id generated by mybatis-plus by default is the self-defined snowflake algorithm //The id auto-increment method provided by the database The way to configure id auto-increment in yml: set to auto auto-increment: id-type:auto } }
open mp log
After running the test program, the console prints sql statements and precompiled parameters and results.
If you don’t open it, there will only be results.
mybatis-plus: global-config: db-config: id-type: auto configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #output console
Pagination query of mp
Configure paging interception:
Mp is implemented by splicing sql statements through interceptors when performing queries:
Let’s first create an interceptor package: create a configuration class for the interceptor: MPConfig:
The configuration class is placed in the package and subpackage where the boot class is located before it can be read and loaded into the spring container:
@Configuration public class MPConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return interceptor; } }
For the configuration class definition, see Spring for details
It will splice page(1, 5) with the limit of sql
The Page object of mp
@SpringBootTest(classes = SpringbootBeginQuickstartApplication.class) class SpringbootBeginQuickstartApplicationTests { @Autowired private BookMapper bookMapper; @Test void contextLoads() { Page page = new Page(1, 5); System.out.println(bookMapper.selectPage(page,null)); //The id generated by mybatis-plus by default is the self-defined snowflake algorithm //The id auto-increment method provided by the database The way to configure id auto-increment in yml: set to auto auto-increment: id-type:auto System.out.println(page);//com.baomidou.mybatisplus.extension.plugins.pagination.Page@6413d7e7 System.out.println(page.getCurrent());//1 System.out.println(page.getSize());//5 System.out.println(page.getTotal());//13 System.out.println(page.getPages());//3 System.out.println(page.getRecords());//[Book(id=2, name=ghet, price=78), Book(id=3, name=ddd, price=12), Book(id= 4, name=ddd, price=12), Book(id=5, name=ddd, price=12), Book(id=6, name=ddd, price=12)] } }
conditional query
The used like% precompiled and spliced sql
@SpringBootTest(classes = SpringbootBeginQuickstartApplication.class) class SpringbootBeginQuickstartApplicationTests { @Autowired private BookMapper bookMapper; @Test void contextLoads() { String name="ddd"; QueryWrapper<Book> qw = new QueryWrapper<>(); qw.like("name", name);//actually, name may be null //qw.eq , qw.ne , lt , gt , le , ge , between , group List<Book> bookList = bookMapper. selectList(qw); System.out.println(bookList); //To prevent the parameter name from being wrongly written, we can use the Qw query of the lambda expression: LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>(); //if(name!=null)lqw.like(Book::getName,name);//Method reference: Just ensure that the input parameters of the lambda can be put into the input parameters of the member method getName of the Book class. lqw. like(name != null, Book::getName, name); List<Book> books = bookMapper. selectList(lqw); System.out.println(books); } }
For the above paging query, you can also get the country qw or lqw
System.out.println(bookMapper.selectPage(page,qw or lqw));
MP simplifies the business layer Service layer
common service
@Service public class BookServiceImpl implements BookService{ @Autowired private BookMapper bookMapper; public Boolean save(Book book){ return bookMapper.insert(book)>0; } public Boolean update(Book book){ return bookMapper. updateById(book)>0; } public Boolean delete(Integer id){ return bookMapper.deleteById(id)>0; } public Book getById(Integer id){ return bookMapper. selectById(id); } public List<Book> getAll(Integer id){ return bookMapper. selectList(null); } public IPage<Book> getPage(int currentPage,int pageSize){ Page page = new Page(currentPage, pageSize); bookMapper. selectPage(page, null); return page; } }
The service interface layer only needs to inherit
public interface BookService extends IService<Book> { }
In addition to implementing the interface layer, impl also needs to inherit
@Service public class BookServiceImpl extends ServiceImpl<BookMapper,Book> implements BookService{ }
ctrl + f12 check the first box, you can see the inherited method inside
Some methods of the mp business layer are used directly, and those that are not are written. Try not to have the same name as the business layer method of Mp, you can use @Override to check whether there is a duplicate name override.
Then you can inject the test class into the service interface and test it.
Presentation layer development
@RestController//restful style controller @RequestMapping("/books") public class BookController { @Autowired private BookService bookService; @GetMapping public List<Book> getAll(){ return bookService. list(); } @PostMapping public Boolean save(@RequestBody Book book){//RequestBody receives json return bookService. save(book); } @PutMapping public Boolean update(@RequestBody Book book){//RequestBody receives json return bookService. updateById(book); } @DeleteMapping("/{id}") public Boolean delete(@PathVariable Integer id){//RequestBody receives json return bookService. removeById(id); } @GetMapping("/{id}") public Book getById(@PathVariable Integer id){//RequestBody receives json return bookService. getById(id); } @GetMapping("{currentPage}/{pageSize}") public IPage<Book> getPage(@PathVariable int currentPage, @PathVariable int pageSize){ Page<Book> page = new Page<>(1,5); return bookService. page(page); } }
postman test
select REST action GET /…
Add json data to the POST/PUT request body { “”:””, “”:””}
DELETE request path parameter/1
Consistency processing of presentation layer messages
The query returns the data of list
, the addition returns true, the modification returns true, the deletion returns true, and the pagination query returns IPage
because:
Query the data whose id does not exist, return null, throw an exception during the query process, and return null in the catch.
At this time:
We don’t know whether this null is returned by querying the database or reporting an exception.
We can set a flag to return true if it is a normal query; return false if an exception is reported but not a normal query:
Design the model class of the result returned by the presentation layer, which is used to unify the data format between the backend and the frontend, also known as the frontend and backend data protocol
We need to add a model class that returns the result data:
util package
@Data @NoArgsConstructor @AllArgsConstructor public class R { private Boolean flag; private Object data; public R(Boolean flag) { this.flag = flag; } }
@RestController//restful style controller @RequestMapping("/books") public class BookController { @Autowired private BookService bookService; @GetMapping public R getAll(){ return new R(true, bookService. list()); } @PostMapping public R save(@RequestBody Book book){//RequestBody receives json R r = new R(); boolean flag = bookService. save(book); r. setFlag(flag); return r; } @PutMapping public R update(@RequestBody Book book){//RequestBody receives json return new R(bookService. updateById(book)); } @DeleteMapping("/{id}") public R delete(@PathVariable Integer id){ return new R(bookService. removeById(id)); } @GetMapping("/{id}") public R getById(@PathVariable Integer id){ return new R(true, bookService. getById(id)); } @GetMapping("{currentPage}/{pageSize}") public R getPage(@PathVariable int currentPage, @PathVariable int pageSize){ Page<Book> page = new Page<>(1,5); return new R(true, bookService. page(page)); } }
Now the query will have a status whether it succeeds or fails.
Joint debugging of front and back ends
Let’s not fix this
Pages belong to the front-end server in the front-end and back-end separation structure design
The pages in the single project are placed in the static directory under the resources directory (clean is recommended)
Exception message handling
When an exception is thrown, R will not be returned, and then springmvc exception handling
R under the util package first adds an attribute private String msg;
Create an exception handler under the util package as a springmvc exception handler
@RestControllerAdvice public class ProjectRxceptionAdvice { @ExceptionHandler public R doException(Exception e){ // log //notify operation and maintenance // notify development e.printStackTrace(); return new R("Server failure, please try again later"); } }
A certain resource of the controller randomly creates an exception, and postman accesses the test.
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Cloud native entry skill treeHomepageOverview 14568 people are learning systematically