SpringBoot之----如何在Dao层模拟数据库中的数据

SpringBoot之----如何在Dao层模拟数据库中的数据,第1张

SpringBoot之----如何在Dao层模拟数据库中的数据

1、我列两个例子给大家看,假如是代表部门Dao层:
DepartmentDao.java

package com.wlm.dao;

import com.wlm.pojo.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//部门Dao
@Repository
public class DepartmentDao {
    //模拟数据库中的数据
    private static Map departments = null;
    static {
        departments = new HashMap();
        departments.put(101,new Department(101,"java部门"));
        departments.put(102,new Department(102,"python部门"));
        departments.put(103,new Department(103,"c部门"));
        departments.put(104,new Department(104,"c++部门"));
        departments.put(105,new Department(105,"c#部门"));
    }
    //获得所有部门信息
    public Collection getDepartments(){
        return departments.values();
    }
    //通过id得到部门
    public Department getDepartmentById(Integer id){
        return departments.get(id);
    }
    
}

2、假如在要连表使用,就是员工含有部门的员工表数据:
EmployeeDao.java

package com.wlm.dao;

import com.wlm.pojo.Department;
import com.wlm.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//员工Dao
@Repository
public class EmployeeDao {
    //模拟数据库中的数据
    private static Map employees = null;
    //员工有所属部门
    @Autowired
    private DepartmentDao departmentDao;
    static {
        employees = new HashMap();
        employees.put(1001,new Employee(1001,"小吴1","1001@qq.com",0,new Department(101,"java部门")));
        employees.put(1002,new Employee(1002,"小张2","1002@qq.com",1,new Department(102,"python部门")));
        employees.put(1003,new Employee(1003,"小陈3","1003@qq.com",0,new Department(103,"c部门")));
        employees.put(1004,new Employee(1004,"小金4","1004@qq.com",1,new Department(104,"c++部门")));
        employees.put(1005,new Employee(1005,"小彭5","1005@qq.com",0,new Department(105,"c#部门")));
    }
    //主键自增
    private static Integer initId = 1006;
    //增加一个员工
    public void save(Employee employee){
        if (employee.getId()==null){
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        employees.put(employee.getId(),employee);
    }
    //查询全部员工信息
    public Collection getAll(){
        return employees.values();
    }
    //通过id查询员工
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    public void delete(Integer id){
        employees.remove(id);
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5612399.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存