If we have a banner_item table, now we need to find all the data by banner_id.
@Data
public class BannerItem {
private Long id;
private String name;
private String img;
private String keyword;
private Integer type;
private Long bannerId;
}
Copy the code
- QueryWrapper
The most basic way to use it is this
// Query the conditional constructor
QueryWrapper<BannerItem> wrapper = new QueryWrapper<>();
wrapper.eq("banner_id", id);
// Query operation
List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);
Copy the code
We can then introduce lambda to avoid having to hardcode banner_id like this in our code
QueryWrapper<BannerItem> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(BannerItem::getBannerId, id);
List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);
Copy the code
- LambdaQueryWrapper
To simplify lambda use, we can rewrite the LambdaQueryWrapper constructor as follows:
LambdaQueryWrapper<BannerItem> wrapper = new QueryWrapper<BannerItem>().lambda();
wrapper.eq(BannerItem::getBannerId, id);
List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);
Copy the code
We can simplify QueryWrapper
.lambda() again to look like this
LambdaQueryWrapper<BannerItem> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(BannerItem::getBannerId, id);
List<BannerItem> bannerItems = bannerItemMapper.selectList(wrapper);
Copy the code
- Chain query
MyBatis-Plus also provides a chained query that works the same as the code above. However, this method tends to be more showy and less readable than the above code, so you can choose your own method if you want.
List<BannerItem> bannerItems = new LambdaQueryChainWrapper<>(bannerItemMapper)
.eq(BannerItem::getBannerId, id)
.list();
Copy the code
If you want to query only one record, for example, the details of a record by id, use. One (), for example
BannerItem bannerItem = new LambdaQueryChainWrapper<>(bannerItemMapper)
.eq(BannerItem::getId, id)
.one();
Copy the code