实现Spring Data存储库的自定义方法并通过REST公开它们

时间:2014-08-08 10:23:22

标签: java spring rest jpa spring-data

我试图按照1.3 Custom implementations for Spring Data repositories中的描述向我的Spring Data存储库PersonRepository添加自定义方法,并通过REST公开这些方法。初始代码来自Accessing JPA Data with REST示例,这里是添加/修改类的代码:

interface PersonRepositoryCustom {
  List<Person> findByFistName(String name);
}

class PersonRepositoryImpl implements PersonRepositoryCustom, InitializingBean {
  @Override
  public void afterPropertiesSet() throws Exception {
    // initialization here
  }
  @Override
  public List<Person> findByFistName(String name) {
    // find the list of persons with the given firstname
  }
}

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
  List<Person> findByLastName(@Param("name") String name);  
}

当我运行应用程序并访问http://localhost:8080/portfolio/search/时,我得到以下响应正文:

{
  "_links" : {
    "findByLastName" : {
      "href" : "http://localhost:8080/people/search/findByLastName{?name}",
      "templated" : true
     }
  }
}

为什么findByFirstName即使在PersonRepository界面中可用,也未公开?

此外,有没有办法动态/编程地添加要通过REST公开的资源库?

7 个答案:

答案 0 :(得分:24)

两天后,我以这种方式解决了。

自定义存储库界面:

public interface PersonRepositoryCustom {
    Page<Person> customFind(String param1, String param2, Pageable pageable);
}

自定义存储库实施

public class PersonRepositoryImpl implements PersonRepositoryCustom{

    @Override
    public Page<Person> customFind(String param1, String param2, Pageable pageable) {
        // custom query by mongo template, entity manager...
    }
}

Spring Data Repository:

@RepositoryRestResource(collectionResourceRel = "person", path = "person")
public interface PersonRepository extends MongoRepository<Person, String>, PersonRepositoryCustom {
    Page<Person> findByName(@Param("name") String name, Pageable pageable);
}

Bean资源表示

public class PersonResource extends org.springframework.hateoas.Resource<Person>{

    public PersonResource(Person content, Iterable<Link> links) {
        super(content, links);
    }
}

资源汇编程序

@Component
public class PersonResourceAssembler extends ResourceAssemblerSupport<Person, PersonResource> {

    @Autowired
    RepositoryEntityLinks repositoryEntityLinks;

    public PersonResourceAssembler() {
        super(PersonCustomSearchController.class, PersonResource.class);
    }

    @Override
    public PersonResource toResource(Person person) {
        Link personLink = repositoryEntityLinks.linkToSingleResource(Person.class, person.getId());
        Link selfLink = new Link(personLink.getHref(), Link.REL_SELF);
        return new PersonResource(person, Arrays.asList(selfLink, personLink));
    }

}

自定义Spring MVC控制器

@BasePathAwareController
@RequestMapping("person/search")
public class PersonCustomSearchController implements ResourceProcessor<RepositorySearchesResource> {

    @Autowired
    PersonRepository personRepository;

    @Autowired
    PersonResourceAssembler personResourceAssembler;

    @Autowired
    private PagedResourcesAssembler<Person> pagedResourcesAssembler;

    @RequestMapping(value="customFind", method=RequestMethod.GET)
    public ResponseEntity<PagedResources> customFind(@RequestParam String param1, @RequestParam String param2, @PageableDefault Pageable pageable) {
        Page personPage = personRepository.customFind(param1, param2, pageable);
        PagedResources adminPagedResources = pagedResourcesAssembler.toResource(personPage, personResourceAssembler);

        if (personPage.getContent()==null || personPage.getContent().isEmpty()){
            EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
            EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(Person.class);
            List<EmbeddedWrapper> embedded = Collections.singletonList(wrapper);
            adminPagedResources = new PagedResources(embedded, adminPagedResources.getMetadata(), adminPagedResources.getLinks());
        }

        return new ResponseEntity<PagedResources>(adminPagedResources, HttpStatus.OK);
    }

    @Override
    public RepositorySearchesResource process(RepositorySearchesResource repositorySearchesResource) {
        final String search = repositorySearchesResource.getId().getHref();
        final Link customLink = new Link(search + "/customFind{?param1,param2,page,size,sort}").withRel("customFind");
        repositorySearchesResource.add(customLink);
        return repositorySearchesResource;
    }

}

答案 1 :(得分:21)

这些方法没有暴露的原因是你基本上可以自由地在自定义存储库方法中实现任何你想要的东西,因此无法推断正确的HTTP方法来支持该特定资源。

在你的情况下,使用普通GET可能没问题,在其他情况下它可能必须是POST,因为该方法的执行有副作用。

目前的解决方案是制作一个自定义控制器来调用存储库方法。

答案 2 :(得分:8)

对于GET方法,我使用了以下方法:

  • 在Repository(LogRepository.java)
  • 中创建一个虚拟@Query方法
  • 使用声明的相同方法(LogRepositoryCustom.java)
  • 创建自定义界面
  • 创建自定义接口(LogRepositoryImpl.java)的实现

使用这种方法,我不必管理预测和资源组装。

@RepositoryRestResource(collectionResourceRel = "log", path = "log")
public interface LogRepository extends PagingAndSortingRepository<Log, Long>, 
                                       LogRepositoryCustom {
    //NOTE: This query is just a dummy query
    @Query("select l from Log l where l.id=-1")
    Page<Log> findAllFilter(@Param("options") String options,
        @Param("eid") Long[] entityIds,
        @Param("class") String cls,
        Pageable pageable);

}

public interface LogRepositoryCustom {

    Page<Log> findAllFilter(@Param("options") String options,
        @Param("eid") Long[] entityIds,
        @Param("class") String cls,
        Pageable pageable);
}

在实现中,您可以自由使用存储库方法或直接转到持久层:

public class LogRepositoryImpl implements LogRepositoryCustom{

    @Autowired
    EntityManager entityManager;

    @Autowired
    LogRepository logRepository;

    @Override
    public Page<Log> findAllFilter(
        @Param("options") String options,
        @Param( "eid") Long[] entityIds,
        @Param( "class"   ) String cls,
        Pageable pageable) {

        //Transform kendoui json options to java object
        DataSourceRequest dataSourceRequest=null;
        try {
            dataSourceRequest = new ObjectMapper().readValue(options, DataSourceRequest.class);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }


        Session s = entityManager.unwrap(Session.class);
        Junction junction = null;
        if (entityIds != null || cls != null) {
            junction = Restrictions.conjunction();
            if (entityIds != null && entityIds.length > 0) {
                junction.add(Restrictions.in("entityId", entityIds));
            }
            if (cls != null) {
                junction.add(Restrictions.eq("cls", cls));
            }
        }

    return dataSourceRequest.toDataSourceResult(s, Log.class, junction);
}

答案 3 :(得分:2)

答案是你没有遵循指示。您的PersonRepository必须同时延长PagingAndSortingRepository<Person, Long>PersonRepositoryCustom才能实现您所追求的目标。见https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#repositories.custom-implementations

答案 4 :(得分:1)

我们使用的另一个选项是为您的特定存储类型实现自定义存储库工厂。

您可以从RepositoryFactoryBeanSupport扩展,构建您自己的PersistentEntityInformation并在默认的repo impl中处理CRUD操作,以获取自定义数据存储类型。例如,请参阅JpaRepositoryFactoryBean。您可能需要总共实现大约10个类,但它可以重复使用。

答案 5 :(得分:0)

尝试使用

class PersonRepositoryCustomImpl implements PersonRepositoryCustom, InitializingBean {
    ...
}

答案 6 :(得分:0)

实现类名称应为PersonRepositoryCustomImpl,而不是PersonRepositoryImpl