在春季启动中无法获取用户名

时间:2019-02-11 15:26:59

标签: java spring spring-boot spring-boot-jpa

问题是:当我使用JpaRepository并使用一种方法通过用户名来获取用户时,如以下代码所示:

public interface UserRepository extends JpaRepository<User, Integer> {

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

这是实体:

@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;
}   

这是控制器:

@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);
    }
}

这是json的全部数据,同时从db获取所有用户:

enter image description here

当我从名称(URL:localhost/u/{username})获得用户时:

enter image description here

我确保从网址输入的名称正确。

4 个答案:

答案 0 :(得分:1)

您的UserController中路径/u/{name}有重复的映射。 getUserByIdgetUsernameAndPasswordByName具有相同的端点。

答案 1 :(得分:1)

错误指出您已经映射了两个具有相似路径的RestController方法:

getUsernameAndPasswordByNamegetUserById

尝试使用不同的@GetMapping值,例如:@GetMapping("/name/{name}"), @GetMapping("/id/{id}")

答案 2 :(得分:1)

您有两个具有相同映射的方法

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

这对于春天来说是模棱两可的; 只需将其中一个映射更改为以下内容即可:

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

答案 3 :(得分:1)

由于映射不明确,Spring无法区分getUsernameAndPasswordByName(String)getUserById(Integer)

尝试对getUsernameAndPasswordByName(String)方法使用查询参数,它会更像--

    getUsernameAndPasswordByName(@PathVariable("name") String name) 

    //and

    getUserById(@PathVariable("id") int id)