系统自动生成工号

新增员工基本信息:新增一名新员工基本信息,员工基本信息包括;工号(数据库中工保持唯一、由系统自动生成、生成规则:学号由八位数字组成、开头以“2019XXXX”,其中XXXX为四位依次递增的数字序号例如:“20190001、20190002……”)
定义两个函数,一个getLastJobId获取数据库中最大工号,一个generateJobId生成下一个工号。
在Dao层

@Select("SELECT jobid FROM yuan ORDER BY jobid DESC LIMIT 1")
String getLastJobId();

加入这条语句。
Service层
Yuan selectByJobid(String jobid);
String generateJobId(String jobid);
ServiceImpl层
public String getLastJobId() {
try (SqlSession sqlSession = MybatisUtil.getSqlSession()) {
YuanMapper yuanMapper = sqlSession.getMapper(YuanMapper.class);
String lastJobId = yuanMapper.getLastJobId();
if (lastJobId == null || lastJobId.isEmpty()) {
return "20190000"; // 返回一个默认值
}
return lastJobId;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

@Override
public String generateJobId(String jobid) {
String lastJobId = getLastJobId();
int nextSeq = 1;
int year = Calendar.getInstance().get(Calendar.YEAR);

    if (lastJobId != null && lastJobId.length() > 4) {
        try {
            int lastSeq = Integer.parseInt(lastJobId.substring(4));
            nextSeq = lastSeq + 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            nextSeq = 1;
        }
    }

    return String.format("%d%04d", year, nextSeq);
}

AddServlet层
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取请求参数
String name = req.getParameter("name");
String sex = req.getParameter("sex");
String department = req.getParameter("department");
String birthday = req.getParameter("birthday");
String role = req.getParameter("role");
int password = Integer.parseInt(req.getParameter("password"));

    // 使用service层生成工号

  String jobid =yuanService.generateJobId( yuanService.getLastJobId());

    // 创建员工对象
    Yuan yuan = new Yuan(jobid, name, sex, birthday, department, role, password);

    // 调用service层添加员工
    yuanService.addyuan(yuan);

    // 重定向回主页面
    resp.sendRedirect("indexservlet");
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 显示添加员工页面
    Context context = new Context();

// req.getRequestDispatcher("/addservlet.html").forward(req, resp);
ThymeleafUtil.process("addservlet.html", context, resp.getWriter());
}
}

posted @ 2024-12-18 17:37  雨花阁  阅读(16)  评论(0编辑  收藏  举报