在 MyBatis Plus 中,使用 Map 来实现数据库操作

发布时间 2023-08-01 09:58:04作者: 小张在搬砖

假设我们有一个数据库表 Student,包含字段 id、name 和 age,下面是使用 MyBatis Plus 和 Map 实现增删改查的示例:

1、插入数据:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public void insertStudent() {
        Map<String, Object> studentMap = new HashMap<>();
        studentMap.put("name", "John");
        studentMap.put("age", 20);

        // 插入数据
        studentMapper.insert(studentMap);
    }
}

2、查询数据:

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public List<Map<String, Object>> getStudents() {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name", "age").eq("age", 20);

        // 查询数据
        return studentMapper.selectMaps(queryWrapper);
    }
}

3、更新数据:

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public void updateStudent(Long id) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("name", "Updated Name");
        updateMap.put("age", 25);

        // 更新数据
        studentMapper.updateById(id, updateMap);
    }
}

4、删除数据:

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public void deleteStudent(Long id) {
        // 删除数据
        studentMapper.deleteById(id);
    }
}

5、分页查询

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StudentService {

    @Autowired
    private StudentMapper studentMapper;

    public List<Map<String, Object>> getStudentsByPage(int pageNum, int pageSize) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name", "age").eq("age", 20);

        // 构建分页对象
        Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);

        // 分页查询
        return studentMapper.selectMapsPage(page, queryWrapper).getRecords();
    }
}