mybatisplus使用常见场景,给我写多一些常用操作题,并给出答案
时间: 2024-04-25 10:03:31 浏览: 37
Mybatis项目中应用和常见问题
1. 查询所有记录并按照某个字段排序
```java
List<User> userList = userMapper.selectList(new QueryWrapper<User>().orderByAsc("age"));
```
2. 分页查询记录
```java
Page<User> page = new Page<>(1, 10);
IPage<User> userPage = userMapper.selectPage(page, new QueryWrapper<User>());
List<User> userList = userPage.getRecords();
```
3. 根据条件删除记录
```java
int deleteCount = userMapper.delete(new QueryWrapper<User>().eq("age", 18));
```
4. 根据主键更新记录
```java
User user = new User();
user.setId(1L);
user.setName("张三");
int updateCount = userMapper.updateById(user);
```
5. 根据条件更新记录
```java
User user = new User();
user.setName("张三");
int updateCount = userMapper.update(user, new QueryWrapper<User>().eq("age", 18));
```
6. 插入记录并返回主键
```java
User user = new User();
user.setName("张三");
user.setAge(18);
userMapper.insert(user);
Long id = user.getId();
```
7. 批量插入记录
```java
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setName("张三");
user1.setAge(18);
User user2 = new User();
user2.setName("李四");
user2.setAge(20);
userList.add(user1);
userList.add(user2);
userMapper.insertBatch(userList);
```
8. 根据主键查询记录
```java
User user = userMapper.selectById(1L);
```
9. 根据条件查询单条记录
```java
User user = userMapper.selectOne(new QueryWrapper<User>().eq("name", "张三"));
```
10. 根据条件查询记录数
```java
int count = userMapper.selectCount(new QueryWrapper<User>().eq("age", 18));
```
阅读全文