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> {
}
and services like this:
@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;
}
}
I'm using 12 entities and everyone has the same service methods.
Thanks!
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.
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)...
All in all, I'd recomend you to organize your services accordingly your business logic instead of a bunch of CRUDs