In Mybatis Plus, it is often necessary to query according to the conditions, but sometimes it does not need to query all fields, only a few columns. At this time, you can use Wrapper's select method to achieve it. Below I will introduce in detail how to use Wrapper to query certain columns, not certain columns.
1. Basic usage
You need to create an entity class, such as User, and then create a corresponding Mapper interface, such as UserMapper. Next, a Wrapper can be used in the Service layer or the Controller layer to query.
@Service public class UserService { @Autowired private UserMapper userMapper; public List<User> selectColumns(Wrapper<User> wrapper) { return (wrapper); } }
In the above code, a selectColumns method is defined, which receives a Wrapper parameter and then calls the selectList method of userMapper for querying.
2. Query a few columns
If you want to query the name and age fields in the User entity, you can write it like this:
Wrapper<User> wrapper = new QueryWrapper<>(); ("name", "age"); List<User> users = (wrapper);
In the above code, a QueryWrapper object is created, and then the select method is called to pass in the field name to be queryed, and finally the selectColumns method of userService is called for query.
3. Do not query certain columns
If you do not want to query the id field in the User entity, you can write it like this:
Wrapper<User> wrapper = new QueryWrapper<>(); (, i->!().equals("id")); List<User> users = (wrapper);
In the above code, a QueryWrapper object is created, and then the select method is called to pass in the field name to be queryed. Then the notSelect method is called to pass in the field name that you do not want to query, and finally the selectColumns method of userService is called to query.
4. Mybatis-plus only query some fields.
Method 1: Just query the two fields name and phone: use the select() method of queryWrapper to specify the field to query
@Test public void selectByWrapper1() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); ("name", "phone").eq("age",25); List<User> users = (queryWrapper); (::println); }
Method 2: Query the data of all fields except age and address: Use the select() method of queryWrapper
@Test public void selectByWrapper2() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); (, info -> !().equals("age") && !().equals("address")).eq("name","jack"); List<User> users = (queryWrapper); (::println); }
This is the article about the implementation of Mybatis Plus Wrapper querying some columns. For more information about Mybatis Plus Wrapper querying some columns, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!