问题是:当我使用 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 的全部数据:
当我从名称(网址:)获取用户时localhost/u/{username}
:
我保证从 URL 输入的名称是正确的。
小唯快跑啊
慕妹3242003
心有法竹
浮云间
相关分类