代码之家  ›  专栏  ›  技术社区  ›  Matthijs Mennens

休息服务项目结构

  •  1
  • Matthijs Mennens  · 技术社区  · 6 年前

    我和一个同事在一个项目中工作,他告诉我在创建休息服务时应该创建三个级别。如果这是“正常”的,如果我用的是正确的方式,有人能解释我吗?他从未解释过原因,几周后离开了公司。

    第一级:资源

    我想你就是在这里接到请求的(GET、POST、PUT等)

    二级:服务

    我会理解这里发生的计算吗?

    第三级:存储库

    他把所有与 数据库。

    例如,假设我们有一个具有属性“level”的实体“employee”。根据你的水平,你会得到不同的奖金。我们要计算奖金并通过休息服务返回。

    资源方法如下所示:

    @GET
    @Path("/id/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public double findBonusById(@PathParam("id") long id) {
        return employeeService.findBonusById(id);
    }
    

    服务方法如下所示:

    public double findBonusById(long id) {
        int level = employeeRepository.findLevelById(id);
        double initialBonus = 2563;
        return level * initialBonus;
    }
    

    存储库方法如下所示:

    public int findLevelById(long id) {
        return getEntityManager().createNamedQuery("Employee.findLevelById").setParameter("id", id).getSingleResult();
    }
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   Ryuzaki L    6 年前

    在你的例子中,这就是所谓的分层架构

    控制器 哪个处理请求

    @GET
    @Path("/id/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public double findBonusById(@PathParam("id") long id) {
    return employeeService.findBonusById(id);
    }
    

    服务 是一个在控制器和存储库之间通信的层

    public double findBonusById(long id) {
    int level = employeeRepository.findLevelById(id);
    double initialBonus = 2563;
    return level * initialBonus;
    }
    

    业务 这是可选层,取决于需求,您可以在此层中拥有所有业务逻辑。

    double initialBonus = 2563;
    return level * initialBonus;
    

    存储库 就像你说的 This is where he put all the statements that connect with the Database.

    public int findLevelById(long id) {
    return getEntityManager().createNamedQuery("Employee.findLevelById").setParameter("id", id).getSingleResult();
     }
    
        2
  •  2
  •   Yogendra Mishra    6 年前

    是的,Matthijs,这很正常。当构建任何与Web服务相关的项目时,人们更喜欢的是不同的“分离层”。即 layer architecture

    1. 管制员:您的请求到达的地方。

      @GET @Path("/id/{id}") @Produces(MediaType.APPLICATION_JSON) public double findBonusById(@PathParam("id") long id) { return employeeService.findBonusById(id); }

    2. 服务:执行业务逻辑的位置

      public double findBonusById(long id) { int level = employeeRepository.findLevelById(id); double initialBonus = 2563; return level * initialBonus; }

    3. 存储库:与数据库通信的位置。

      public int findLevelById(long id) { return getEntityManager().createNamedQuery("Employee.findLevelById").setParameter("id", id).getSingleResult(); }

    这些是人们通常遵循的一些标准,但是可能存在更多的分离层。