我正在使用Spring Boot和Spring Data Jpa开发Web应用程序。我想要做的是编写一个自定义查询方法,该方法在给定用户名的情况下从数据库中检索用户。这是我的AppUserRepository接口,扩展了CrudRepository接口:
@Repository
public interface AppUserRepository extends CrudRepository<AppUser,Integer>{
public AppUser findOneByUsername(@Param("username") String username);
}
这是AppUser类:
@Entity(name="appUser")
@Table(name="appUser")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="nume")
@NotNull
private String nume;
@Column(name="prenume")
@NotNull
private String prenume;
@Column(name="username", unique=true)
@NotNull
private String username;
@Column(name="password")
@NotNull
private String password;
@Column(name="email", unique=true)
@NotNull
private String email;
@Column(name="authorities")
@NotNull
private String authorities;
public AppUser() {
}
public AppUser(Long id, String nume, String prenume, String username, String password, String email,
String authorities) {
super();
this.id = id;
this.nume = nume;
this.prenume = prenume;
this.username = username;
this.password = password;
this.email = email;
this.authorities = authorities;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNume() {
return nume;
}
public void setNume(String nume) {
this.nume = nume;
}
public String getPrenume() {
return prenume;
}
public void setPrenume(String prenume) {
this.prenume = prenume;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAuthorities() {
return authorities;
}
public void setAuthorities(String authorities) {
this.authorities = authorities;
}
}
然后,我已经定义了AppUserController,我在其中实现了方法 getUserByUsername 。
@RestController
@RequestMapping(value="/user")
public class AppUserController {
@Autowired
private AppUserRepository appUserRepository;
@RequestMapping(value="/all", method=RequestMethod.GET)
public ResponseEntity getAllUsers() {
return new ResponseEntity((List)appUserRepository.findAll(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(value="/{username}", method=RequestMethod.GET)
public ResponseEntity getUserByUsername(@PathVariable("username") String username) {
return new ResponseEntity<AppUser>(appUserRepository.findOneByUsername(username), new HttpHeaders(), HttpStatus.OK);
}
当我测试方法时,我正在调用http://localhost:8080/user/existingUsername,其中 existingUsername 是我的数据库中已存在的用户名。
问题是查询的结果始终为null,即使用户名存在。
我为该方法尝试了其他名称,例如 findAppUserByUsername 或 findByUsername ,但它们都不起作用。此外, getAllUsers 方法工作正常。
更新:我做了一些调试,我意识到问题是我可以将整个用户名作为路径变量发送,因为它们遵循模式 name.surname 以及点之后的内容总是被忽略。
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试通过/ all更改uri caus的歧义 像这样的/ name / {usename}