How is ‘distinct’ used in MyBatis Plus?

In MyBatis Plus, the distinct method can be used to achieve deduplication. It can be used on QueryWrapper or LambdaQueryWrapper objects.

Example usage:

// 使用QueryWrapper的distinct方法
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("id", "name").distinct(true).eq("age", 18);
List<User> userList = userMapper.selectList(queryWrapper);

// 使用LambdaQueryWrapper的distinct方法
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.select(User::getId, User::getName).distinct(true).eq(User::getAge, 18);
List<User> userList = userMapper.selectList(lambdaQueryWrapper);

In the above example, the distinct(true) method is used to eliminate duplicates from the query results and only return unique records. Specify the fields to be queried in the select method, and then add query conditions using the eq method.

Note: The distinct method only removes duplicates from the specified fields; if no fields are specified, duplicates will be removed from all fields by default.

bannerAds