Search code examples
restjpaspring-bootnamed-query

IllegalArgumentException: NamedQuery using Spring JPA


I am using namedquery for rest api using Spring JPA. The named query is implemented in my entity class:

@Entity
@Table(name="SPECIMEN_TB")
@NamedQueries({
    @NamedQuery(name="SpecimenTb.findBySpecimenNo", query="select s from SpecimenTb s where s.specimenNo = :specimenNo"),
})

public class SpecimenTb implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SPECIMEN_TB_ROWID_GENERATOR")
    @Column(name="ROW_ID")
    private long rowId;

    @Column(name="SPECIMEN_NO", unique = true)
    private String specimenNo;

My controller looks like this:

@RestController
public class RistoreController {
    @Autowired
    private RistoreService ristoreService;

    @RequestMapping(
            value = "/ristore/foundation/{specno}",
            method = RequestMethod.GET,
            produces = "application/json")
    public ResponseEntity<SpecimenTb> getFmSpecimen(@PathVariable("specno") String specno) {
        List<SpecimenTb> specimens = ristoreService.findBySpecimenNo(specno);
        if (specimens == null) {
            return new ResponseEntity<SpecimenTb>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<SpecimenTb>(specimens.get(0), HttpStatus.OK);
    }

I have a service bean which calls JPA repository findBySpecimenNo method.

@Service
public class RistoreServiceBean implements RistoreService {

    @Autowired
    private SpecimenRepository specimenRepository;

    @Override
    public List<SpecimenTb> findAll() {
        List<SpecimenTb> specimens = specimenRepository.findAll();
        return specimens;
    }

    @Override
    public List<SpecimenTb> findBySpecimenNo(String specimenNo) {
        List<SpecimenTb> specimens = specimenRepository.findBySpecimenNo(specimenNo);
        return specimens;
    }

When I start the Spring Boot Application and type in the url "http://localhost:8080/ristore/foundation/SKM1", I got the following error:

java.lang.IllegalArgumentException: Parameter with that position [1] did not exist

What did I do wrong?


Solution

  • Looks like you can't use a named parameter with the @NamedQuery based on the docs I read. Have you tried with ?1 instead?

    Reason that named parameter doesn't work is that you also have to add the annotation on the method parameter so Spring knows which parameter matches to what placeholder in the query.