[英]Service layer in Java or Only Repository
If i have Spring data repository which includes save, delete and modify operations.如果我有包含保存、删除和修改操作的 Spring 数据存储库。 Should I create the following methods operations in service layer?
我应该在服务层创建以下方法操作吗? And adding annotation
@Transactional
?并添加注释
@Transactional
? Or leave them as is?还是让他们保持原样? Or should I have them in repository layer?
或者我应该将它们放在存储库层中吗?
Example service示例服务
@Service
public class RepositoryOperations{
@Autowired
ProductRepository productRepository;
@Transactional
public void saveProduct(){
productRepository.save();
}
...
}
I think that you are using a good approach for your code.我认为您正在为您的代码使用一种好的方法。 You can create a service layer that will invoke the product repository methods in order to separate responsibilities (business from data logic).
您可以创建一个服务层,它将调用产品存储库方法以分离职责(业务与数据逻辑)。
A 3-layered architecture describes your approach as follows: 3 层架构描述您的方法如下:
In order to prevent any inconsistent in your saveProduct() service method when a problem occurs, you can use the @Transactional annotation in order to rollback all the changes made by your method in the database, so i consider it's a good practice use that annotation when you are working with writing operations in database.为了防止出现问题时您的 saveProduct() 服务方法不一致,您可以使用 @Transactional 注释来回滚您的方法在数据库中所做的所有更改,所以我认为使用该注释是一个很好的做法当您在数据库中进行写入操作时。
We keep three layers generally.我们一般保留三层。
Annotate your dao layer with annotation @Repository
使用注释
@Repository
注释您的 dao 层
Annotate your service layer with annotation @Service
使用注释
@Service
注释您的服务层
Annotate your controllers with annotation @Controller
or @RestController(in case you have REST APIs)使用注释
@Controller
或 @RestController 注释您的控制器(如果您有 REST API)
@Transactional
annotation is used when you want a code to be rolled back if it fails. @Transactional
注解在你希望代码失败时回滚时使用。 If your service places three dao calls for three different operations and you want all or none of those three operations to be performed, annotate your service method with @Transactional
如果您的服务为三个不同的操作放置了三个 dao 调用,并且您希望执行这三个操作中的全部或不执行,请使用
@Transactional
注释您的服务方法
Same applies for dao methods.同样适用于 dao 方法。
So you have now fair amount of information to decide upon.所以你现在有相当多的信息可以决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.