Mapper中的基本查询
Continue to use the database table and entity class created in the last blog:
create table users (
id integer primary key not null auto_increment,
username varchar(50) not null,
password varchar(100) not null,
question varchar(150),
answer varchar(50)
);
@TableName(value = "users")
public class AppUser {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String question;
private String answer;
}
public interface AppUserMapper extends BaseMapper<AppUser> {
}
selectById 与 selectBatchIds
AppUser appUser = appUserMapper.selectById(2);
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
List<AppUser> users = appUserMapper.selectBatchIds(ids);
通过Map - selectByMap
通过Map来封装查询条件,map中写的是数据表中的列名,而非实体类的属性名。
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("username", "jisu");
columnMap.put("question", "What is my name?");
List<UserInfo> users = userInfoMapper.selectByMap(columnMap);
使用QueryWrapper
QueryWrapper是一个查询构造器,相当于Where条件。
QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
queryWrapper.like("username","ha").like("question", "What");
QueryWrapper的方法见下表:
| method name | note | example |
|---|---|---|
| eq | = | eq("name", "wong") |
| ne | != | ne("name", "wong") |
| gt | > | gt("age", 18) |
| ge | >= | |
| lt | < | |
| le | <= | |
| or | OR | 紧接着的下一个方法不是用ADD连接eq("id", 1).or().eq(age, 18) |
| between | ||
| notBetween | ||
| like | ||
| notLike | ||
| likeLeft | ||
| likeRight | ||
| inSql | ||
| notInSql | ||
| groupBy | ||
| orderByAsc | ||
| orderByDesc |
Top comments (0)