0

I'm trying to expose simple REST-API for data querying with two optional params available:

GET myServ/greeting?message=X&type=Y

Unfortunately I'm stucked with proper spring-data configuration to enable proper querying. Below methods should

  • GET myServ/greeting - return every greeting
  • GET myServ/greeting?message=X - return every greeting with message=X
  • GET myServ/greeting?type=Y - return every greeting with type=Y
  • GET myServ/greeting?message=X&type=Y - return every greeting with message=X AND type=Y

Simple as it can be - but I don't want to write any if-else code in my controller! Is there any out-of-box configuration enabled which will result in below behavior? I tried different mix of standard JpaReposotory methods and ExampleMatchers but still I cannot make it work.

My model:

package my.model;

import lombok.*; 
import javax.persistence.*;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@ToString
public class Greeting {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String message;
    private String type;
}

repository:

package my.repository;

import my.model.Greeting;
import org.springframework.data.jpa.repository.JpaRepository;

public interface GreetingRepository extends JpaRepository<Greeting, Long>{
}

web-controller:

package my.web;

import my.model.Greeting;
import my.repository.GreetingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class GreetingController {

    @Autowired
    private GreetingRepository repository;

    @RequestMapping(value = "/greeting", method = GET)
    public List<Greeting> get(
            @RequestParam(value = "message", required = false) String message,
            @RequestParam(value = "type", required = false) String type ){

        return HOW_TO_DO_IT??;
    }
}
Tom
  • 181
  • 1
  • 8

1 Answers1

0

If the entity is that simple use Query By Example. Your repository needs to extend addtionaly QueryByExampleExecutor<Greeting>. This will add the method findAll(Example<S> example) to your repository. Then you call it like:

Example<Greeting> example = Example.of(new Greeting("someMessage", "aType"));
repo.findAll(example);

Other options are the Criteria API and QueryDSL. All three options are mentioned here.

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119