简体   繁体   English

存储库上的事务

[英]transactions on repositories

My controller looks like this : 我的控制器看起来像这样:

@RequestMapping(value = "/User", method = RequestMethod.GET)
public @ResponseBody String getUser(@RequestParam long id) {
User user = userService.get(id);
return user.name;
}

Where service looks like this 服务看起来像这样

@Transactional(readOnly = true)
public User getUser(long id) {
  return userRepository.get(id);
}

I hear the mantra transactions on service layer , transaction on service layer ; 我听到服务层上的mantra 事务,服务层上的 事务 ; but would it be so bad to inject the repository directly into controller. 但是将存储库直接注入控制器会是如此糟糕。 After first making the repository transactional - with propagation required so it will create a transaction if not already present ? 在第一次创建存储库事务之后 - 需要传播以便创建事务(如果尚未存在)?

This depends on the size of your project and the complexity within it. 这取决于项目的规模和项目的复杂程度。 I feel services work excellent when multiple repositories need to interact. 当多个存储库需要交互时,我觉得服务工作非常好。

For example, a BankAccountService needs to use the AccountRepository to debit/credit an account, while it also needs to use the LedgerRepository to record the transaction. 例如,BankAccountService需要使用AccountRepository来借记/贷记帐户,同时还需要使用LedgerRepository来记录交易。

If your simply performing crud operations, I would not hesitate to put the repository in the controller. 如果您只是简单地执行crud操作,我会毫不犹豫地将存储库放在控制器中。 If your operations are more advanced I would take the service approach. 如果您的操作更先进,我会采取服务方法。 Address your simplest use case and then refactor when more complexity is introduced. 解决最简单的用例,然后在引入更多复杂性时进行重构。 Doing a big design up front often violates the "You Ain't Gonna Need It" principle. 预先做大设计往往违反了“你不需要它”的原则。

Also services are handy when different controllers need to perform the same operation. 当不同的控制器需要执行相同的操作时,服务也很方便。 So if the logic you are creating is controller specific and you do not need to reuse the code, placing the repository in the controller makes sense. 因此,如果您创建的逻辑是特定于控制器的,并且您不需要重用代码,则将存储库放在控制器中是有意义的。 If you will need to duplicate the logic within other controllers a service may be a better option, since it will be reusable. 如果您需要在其他控制器中复制逻辑,则服务可能是更好的选择,因为它可以重复使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM