是否有必要为每个实体创建存储库和服务

是否有必要为每个实体创建存储库和服务

本文介绍了是否有必要为每个实体创建存储库和服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Hibernate + Spring和一个数据库来保存我的实体.我已经在使用 JpaRepository 来创建我的存储库,但是即使那样,似乎我仍然必须为每个实体创建一个扩展JpaRepository的接口.最糟糕的是,我正在为每个实体创建一项服务.他们都非常相似.

I'm using Hibernate+Spring and a database to persist my entities. I'm already using JpaRepository to create my repositories but even then, it seems I must create one interface extending JpaRepository for each entity. Worst, I'm creating one service to each entity. All of them very similar.

有什么方法可以创建通用服务和通用存储库?真的有必要实现它们中的每一个吗?

There's any way to create a generic service and a generic repository? Is it really necessary to implement each one of them?

目前,我有这样的存储库:

By the moment, I have repositories like this:

@Repository
public interface PhaseRepository extends JpaRepository<Phase, Serializable> {

}

以及类似的服务:

@Service
public class PhaseService {
    @Autowired
    PhaseRepository repository;

    @Transactional
    public Phase create(Phase entity) {
        return repository.save(entity);
    }

    @Transactional(rollbackFor = EntityNotFound.class)
    public Phase delete(int id) throws EntityNotFound {
        Phase deleted = repository.findOne(id);
        if (deleted == null) {
            throw new EntityNotFound();
        }
        repository.delete(deleted);
        return deleted;
    }

    @Transactional(rollbackFor = EntityNotFound.class)
    public Phase update(Phase entity) throws EntityNotFound {
        Phase updated = repository.findOne(entity.getId());

        if (updated == null) {
            throw new EntityNotFound();
        }

        repository.saveAndFlush(entity);
        return updated;
    }

    public Phase findById(int id) throws EntityNotFound {
        Phase entity = repository.findOne(id);

        if (entity == null) {
            throw new EntityNotFound();
        }

        return entity;
    }
}

我使用的是12个实体,每个人都有相同的服务方法.

I'm using 12 entities and everyone has the same service methods.

谢谢!

推荐答案

可能您需要12个存储库.但也许您不需要12项服务.服务可以处理对多个存储库的访问.这取决于您的逻辑以及每个实体的重要性".

Probably you'll need the 12 repositories. But maybe you won't need 12 services. A service could handle the access to several repositories. It depends on your logic and how "important" are every entity.

例如,如果您具有实体User和Address,则可以具有UserRepository和AddressRepository.但是只有UserService才能使用addAddress(User user,Address address)...

For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)...

总的来说,我建议您根据业务逻辑而不是一堆CRUD来组织服务

All in all, I'd recomend you to organize your services accordingly your business logic instead of a bunch of CRUDs

这篇关于是否有必要为每个实体创建存储库和服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:36