我正在开发javaSE中的小应用程序,只是为了让我的技能更好.所以我有业务服务(BS进一步),其中一些方法就像registerUser(用户用户),addAmount(长accountId).BS使用dao.假设从WS或其他接口元素调用BS.我有以下DAO:
public interface UserDao {
User getUserByUsername(String username);
void saveUser(User user);
}
public interface AccountDao {
void saveAccount(Account account);
Account getAccountByUserId(Long userId);
}
Run Code Online (Sandbox Code Playgroud)
我的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");
}......
}}
Run Code Online (Sandbox Code Playgroud)
所以我的第一个问题是我应该在哪里检查params等等?在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);
Run Code Online (Sandbox Code Playgroud)
}
是的,检查业务服务中的空值比在Dao中检查它们更好,因为这是一个分层架构,并且在BS中检查发生得更早.
至于为什么"每桌一道" - 好吧,Dao的习惯会随着时间的推移而变得更加复杂,所以如果你现在在"账户"表上有2个操作,将来可能会有10或20个操作因此,一对一的连贯方法更易于管理,也更容易测试.
所以我当然会避免MagicDao.跨表操作的工作是服务的角色(或其他一些模式,如a Facade) - 而不是Dao,至少按照惯例.
此外,现代依赖注入框架使得声明和使用服务中所需的所有Daos变得简单.在业务服务中有5个或更多Daos(每个表一个)没有问题 - 我在代码中看到这种情况很常见.
顺便说一句,你可以IllegalArgumentException在你投掷的地方使用Exception它 - 它更明确,也是一个RuntimeException(因此你不需要声明它throws)
| 归档时间: |
|
| 查看次数: |
1802 次 |
| 最近记录: |