1

When use GET with postman on link http://localhost:8081/api/data/mydatas/admin

i get an empty array. I've also tried adding { "username": "admin" } but it still returns as an empty array.

this is the code in my java service:

@GetMapping("/mydatas/{username}")
    public List<Data> findByUsername(String username) {

        Query q = em.createQuery("select data from Data data where data.username = :username");
        q.setParameter("username", username);
        List<Data> mydatas = q.getResultList();
        return mydatas;
        
        }

However, if i add username = "admin"; as below. It will send back the array with full of data.

    @GetMapping("/mydatas/{username}")
    public List<Data> findByUsername(String username) {

        username = "admin";

        Query q = em.createQuery("select data from Data data where data.username = :username");
        q.setParameter("username", username);
        List<Data> mydatas = q.getResultList();
        return mydatas;
        
        }

What am i doing wrong? Ps i am a novice still struggling with the basics.

1
  • 2
    Try to add @PathVariable to your parameter username. Commented Aug 13, 2020 at 8:53

3 Answers 3

4

add @PathVariable before your parameter like so

@PathVariable String username

With this annotation you are telling Spring to grab username from URL path

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use @PathVariable,

public List<Data> findByUsername(@PathVariable("username") String username)

Comments

0

The @PathVariable annotation should be passed in with the name of the field in speechmarks "" as the argument for findByUsername before "String username"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.