简体   繁体   中英

Spring Data Repository (JPA) - findByXXX using entity relation

A Schedule entity has a one to one relationship with a Market entity as well as some other "simple" properties.

Here is my ScheduleRepository:

@RepositoryRestResource(path = "schedule")
public interface ScheduleRepository extends JpaRepository<Schedule, Long>
{
    Collection<Schedule> findByMarket(Market market);
}

"findByMarket" method works fine when invoking the method programmatically. However, when invoking directly from a web application ( http://localhost:8080/schedule/search/findByMarket ), the request type must be GET.

My question is how do I pass a Market JSON object using GET? Using POST wouldn't be an issues but findXxx methods must use GET. I tried passing something like:

?market={marketId:60}

in the querystring but to no avail.

Not knowing what your controller looks like, I would assume that if you wanted to pass marketId on a get it would look like.

?marketId=60

And your method would look like. The method you use will handle converting to and from JSON.

@Get
@Path("/query")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("marketId") String marketId)

In the documentation it is referenced to use the @Param annotation, so you can call to your rest service giving a query parameter. Here you have an example:

package hello;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

    List<Person> findByLastName(@Param("name") String name);

}

I ended up using a @Query annotation, like jdepedro suggested:

@Query("select s from Schedule s where s.market.marketId = :marketId and s.locale.localeId = :localeId and s.offline >= :offline order by s.placement, s.slot, s.online")
    Collection<Schedule> findByMarket(@Param("marketId") Integer marketId, @Param("localeId") Integer localeId, @Param("offline") Date offline);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM