У меня есть три метода общего доступа ко всему хранилищу findAll()
, pageAll()
и findOneByName()
.В контроллере я использую репозиторий с методом findOneByName (), чтобы проверить, повторяется ли имя пользователя.
Пример sexController
if (genderRepository.findOneByNome(gender.getName()) != null) {
throw new RuntimeException("Name repeated");
}
return new ResponseEntity<>(genderService.save(gender), HttpStatus.CREATED);
Все репозитории имеют три метода в общем виде, поэтому ясоздайте собственный репозиторий для этого.Я пытаюсь реализовать каждый репозиторий с новым методом и расширить ваши общие методы.Это хорошая практика?
CustomRepo
@NoRepositoryBean
public interface CustomRepo<T, ID extends Serializable> extends GenericService<T, ID> {
@Query("SELECT NEW #{#entityName} (t.id,t.name) FROM #{#entityName} as t ORDER BY t.name ASC")
public List<T> findAll();
@Query("SELECT NEW #{#entityName} (t.id,t.name) FROM #{#entityName} as t ORDER BY t.name ASC")
public Page<T> pageAll();
public T findOneByName(String nome);
}
GenericService с методами реализации
public interface GenericService<T, I extends Serializable> {
List<T> findAll();
T getById(Long id);
T create(T entity);
T update(T entity);
void deleteById(Long id);
}
GenderRepository
@Repository
public interface GenderRepository extends CustomRepo<GenderEntity, Long> {
@Query("Select m FROM GenderEntity g JOIN g.manga m where g.id=:id ORDER BY m.name ASC ")
public Page<GenderEntity> findMangaById(@Param("id") Long id, Pageable page);
}
GroupRepository
@Repository
public interface GroupRepository extends GenericService<GroupEntity, Long>{
public Page<GroupEntity> findMangaByIdAutor(@Param("id")Long id, Pageable pageable);
@Query(value="SELECT g FROM GroupEntity g where g.name LIKE :name%")
public Page<GroupEntity> findByLetter(@Param("name") String name, Pageable pageable);
}
AuthorRepository
@Repository
public interface AuthorRepository extends GenericService<AuthorEntity, Long> {
@Query("SELECT NEW AuthorEntity(id,name) FROM AuthorEntity a where a.name like :letra%")
public Page<AuthorEntity> pageAllByLetter(@Param("letra") String name, Pageable pageable);
@Query("Select m FROM AuthorEntity a JOIN a.manga m where a.id=:id ORDER BY m.name ASC")
public Page<AuthorEntity> findMangaById(@Param("id") Long id, Pageable page);
}
AuthorService с реализацией
@Service
public class AuthorService implements AutorRepository{
//Custom impl
}
GenderService
@Service
public class GenderService implements GenderRepository{
//Custom impl
}
GroupService
@Service
public class GrupoService implements GruposRepository {
//Custom Impl
}
Я создал CustomRepo дляметоды commons и GenericService с методиками Crud, возможно ли создать только один интерфейс с методиками commons для расширения хранилища и его реализации?
Каков наилучший способ сделать это?Лучшая практика?