gpt4 book ai didi

java - 无法在 spring boot 中获取用户名

转载 作者:行者123 更新时间:2023-11-29 10:08:42 25 4
gpt4 key购买 nike

问题是:当我使用 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;
}

这是 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);
}
}

这是从数据库中获取所有用户时的 JSON 的全部数据:

enter image description here

当我从名称中获取用户时(url:localhost/u/{username}):

enter image description here

我保证从 URL 输入的名称是正确的。

最佳答案

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

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

这对于 spring 来说是模棱两可的;只需将其中一个映射更改为如下所示:

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

关于java - 无法在 spring boot 中获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com