所有存储库的Spring Data Jpa自定义方法以及每个存储库的新方法

时间:2018-11-21 16:41:19

标签: java spring-boot spring-data-jpa spring-data

我对所有存储库findAll()pageAll()findOneByName()有三种共有的方法。在控制器中,我将存储库与方法findOneByName()一起使用,以检查是否重复用户名。

性别控制器示例

if (genderRepository.findOneByNome(gender.getName()) != null) {
                throw new RuntimeException("Name repeated");
        }
  return new ResponseEntity<>(genderService.save(gender), HttpStatus.CREATED);

所有存储库都有三种共有的方法,因此我为此创建了自定义存储库。我正在尝试使用新方法来实现每个存储库,并扩展您的commons方法。这是一个好习惯吗?

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
}

我使用Crud方法创建了Commons方法和GenericService的CustomRepo,是否有可能只使用Commons方法创建一个接口来扩展存储库并实现?

做到这一点的最佳方法是什么?最佳做法?

0 个答案:

没有答案