【问题标题】:Can DAO be used for multiple tables ?DAO 可以用于多个表吗?
【发布时间】:2017-07-21 16:58:30
【问题描述】:

我正在使用 javaSE 开发小应用程序,只是为了提高我的技能。所以我有业务服务(进一步的BS),其中一些方法如registerUser(User user),addAmount(Long accountId)。 BS 使用 dao。让我们假设 BS 是从 WS 或其他接口元素调用的。我有以下 DAO:

public interface UserDao {

    User getUserByUsername(String username);

    void saveUser(User user);
}

public interface AccountDao {

    void saveAccount(Account account);

    Account getAccountByUserId(Long userId);
}

我的 BS 看起来像

public class FastAccountServiceImpl implements FastAccountService{

private UserDao userDao;
private AccountDao accountDao;

public void registerUser(User user, Account account) throws Exception {
    if (user.getUsername() == null || user.getUsername().isEmpty()) {
        throw new Exception("all params are mandatory");
    }
    if (userDao.getUserByUsername(user.getUsername()) != null) {
        throw new Exception("This user exists");
    }
    userDao.saveUser(user);
    accountDao.saveAccount(account);
}

public void withdrawAmount(Double amount, Long userId) throws Exception {
    if (amount == null || userId == null) {
        throw new Exception("amount and userId are mandatory");
    }
    Account account = accountDao.getAccountByUserId(userId);
    if (account.getAmount() == null || account.getAmount().compareTo(amount) < 1) {
        throw new Exception("Insufficient amount in account");
    }......

}}

所以我的第一个问题是我应该在哪里检查参数是否为 null 等?在BS? 第二个问题是为什么我们应该为每张桌子设置单独的 dao ?我可以为所有表只创建一个 dao。所以在 BS 中只有一个 dao。该 dao 表示如下:

public interface MagicDao {

User getUserByUsername(String username);

void saveUser(User user);

void saveAccount(Account account);

Account getAccountByUserId(Long userId);

}

【问题讨论】:

  • 这对于 StackExchang'es Software Engineering 网站来说可能是一个更好的问题,但请务必阅读他们的规则和帮助中心,以确保您遵循他们的指导方针。
  • @DanielBickler 在引用其他网站时,指出cross-posting is frowned upon 通常会有所帮助
  • @gnat 这很有意义......我认为这个问题可能会因为偏离主题或基于意见而被关闭,因此它不会被交叉发布。这不正确吗?

标签: java spring dao


【解决方案1】:

是的,在业务服务中检查空值比在 Dao 中检查它们更好,因为这是一个分层架构,并且在 BS 中检查发生得更早。

至于为什么“每个表一个 Dao” - 嗯,Dao 的习惯是随着时间的推移变得越来越复杂,所以如果你现在在“Account”表上有 2 个操作,将来很可能有 10 个或 20 次操作,因此统一的 1 对 1 方法更易于管理,也更易于测试。

所以我当然会避免MagicDao。跨表操作的工作是服务的角色(或其他一些模式,如Facade) - 不是道,至少按照惯例。

此外,现代依赖注入框架使声明和使用服务中所需的所有 Daos 变得简单。在业务服务中拥有 5 个或更多 Daos(每个表一个)没有问题 - 我在我使用的代码中很常见。

顺便说一句,你可以在你抛出 Exception 的地方使用 IllegalArgumentException - 它更明确,它也是 RuntimeException(所以你不需要用 throws 声明它)

【讨论】:

  • JavaSE 中也可以使用休眠验证器javacodegeeks.com/2015/07/…
  • @vikingsteve,非常感谢。跨表的服务名称是什么?为什么我们需要 dao 以及何时使用它?
  • FastAccountServiceImpl 是跨表服务的完美示例。我们使用 Dao(数据访问对象)作为抽象层,将“数据库代码”与“服务代码”分开,从而降低您的服务类的复杂性并促进代码的可重用性(其他服务类可以使用相同的 Dao's )。
  • “跨表操作的工作是服务的角色”。不,在服务层中您不编写查询。您将它们写入数据访问层。一个复杂的查询涉及更多的表。现在的问题是:我可以从我的服务层引用这个将触及多个表的 DAO 类吗?
猜你喜欢
  • 2018-11-05
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多