When I was doing a recent video exercise, the list form required in the previous paragraph was rows:[XXX], and the IPage object of Mybatis-Plus returned records by default.

What can we do to get him back to the list form that the front end needs? How do you modify this list?

Please begin my performance ~

Skill one, overload rename!

For the example in the introduction, we need an IPage object that can store a list of data in Rows.

What we need to do is very simple, write a Page class, and then inherit the default Page class, rewrite its methods!

import java.util.List;

public class Page<T> extends com.baomidou.mybatisplus.extension.plugins.pagination.Page {

    public List<T> getRows(a) {
        return super.getRecords();
    }

    public List<T> getRecords(a) {
        return null;
    }

    public Page(long current, long size) {
        super(current, size); }}Copy the code

You read it right, it’s that simple!

  • New getRows() method that returns the result of getRecords() of the parent class.
  • Override the getRecords() method to return null. (Otherwise returning data twice is not very friendly)
  • Write a constructor that calls the parent class with arguments.

Skill two, steal a day to password art!

Here’s the thing: when you retrieve user information, you can’t send the password back to the front end. So how do you modify the retrieved list after using the overloaded rename?

See below!

// Use our custom Page to receive!
Page<Staff> data = baseMapper.selectPage(new Page<Staff>(page, size), query);
List<Staff> staffList = new ArrayList<>();
// Use getRows() to receive the list (with getRecords() is empty because it was overwritten).
for (Staff s: data.getRows()) {
	// Traversal sets the password to empty and adds a new list.
    s.setPassword(null);
    staffList.add(s);
}
// Set with setRecords()! Because you don't have the setRows() method,
// Also, it would be difficult to write a single "rows" object.
// If so, what should getRows() return?
// So this is a straightforward assignment to the native records, and then finally when getRows(),
// The parent class getRecords() will be called to retrieve the value we changed!!
data.setRecords(staffList);
// When returned, the type is strongly changed to IPage.
return Result.ok((IPage<Staff>)data);
Copy the code