Search code examples
javaspringspring-bootjpaspring-boot-jpa

Cannot get username in spring boot


The problem is: When I use JpaRepository and use a method to get the user by username like the code below:

public interface UserRepository extends JpaRepository<User, Integer> {

    @Query(value = "select * from users where username = :name", nativeQuery = true)
    User findUserByName(@Param("name") String name);
}

This is the entity:

@Entity
@Table(name = "users")
@Data
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "username", nullable = false, unique = true)
    private String username;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "joined_date", nullable = false, unique = true)
    @CreatedDate
    private Date joinedDate;

    @Column(name = "password")
    private String password;

    @Column(name = "bio")
    private String bio;

    @Column(name = "email", nullable = false, unique = true)
    private String email;
}   

And this is the controller:

@RestController
@RequestMapping("/u")
public class UserController {
    @Autowired
    private UserRepository repo;
    ....

    @GetMapping("/{name}")
    public ResponseEntity<User> getUsernameAndPasswordByName(@PathVariable("name") String name) {
        User user = repo.findUserByName(name);

        if(user == null) {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

This is the entire data of JSON while getting all user from DB:

enter image description here

And when I get user from name(the url: localhost/u/{username}):

enter image description here

I assure that the name entered from the URL is correct.


Solution

  • You have two methods with the same mapping

    1 - getUsernameAndPasswordByName(@PathVariable("name") String name)
    @GetMapping("/{name}")
    2 - getUserById(@PathVariable("id") int id)
    @GetMapping("/{id}")
    

    and this is ambiguous for spring; just change one of mappings to something like this:

    @GetMapping("/find-by-id/{id}")