参见英文答案 > Are you supposed to have one repository per table in JPA? 1个
我正在使用Hibernate Spring和一个数据库来保存我的实体.我已经在使用JpaRepository来创建我的存储库,但即使这样,我似乎必须为每个实体创建一个扩展JpaRepository的接口.最糟糕的是,我正在为每个实体创建一个服务.他们都非常相似.
有什么方法可以创建通用服务和通用存储库?是否真的有必要实施它们中的每一个?
到目前为止,我有这样的存储库:
@Repository
public interface PhaseRepository extends JpaRepository
和这样的服务:
@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个实体,每个人都有相同的服务方法.
谢谢!
最佳答案
原文链接:https://www.f2er.com/spring/431899.html