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!