I have a User
class like this :
@Data
@Entity
public class User {
@Id
@GeneratedValue
Long userID;
String eMail;
String passwordHash;
//ArrayList<ClassRoom>adminOf=new ArrayList<>();
User() {}
public User(String eMail, String passwordHash) {
this.eMail = eMail;
this.passwordHash = passwordHash;
}
}
And in a LoadDatabase
class I have :
@Bean
CommandLineRunner initDatabase(UserRepository userRepository) {
return args -> {
log.info("Preloading " + userRepository.save(new User("admin@admin.com", "asdasd")));
log.info("Preloading " + userRepository.save(new User("admin@admin.com", "12345")));
};
}
Which give me this :
Now in when I give curl -v localhost:8080/user
this command it gives me this :
Which is pretty correct, although it gives me email
instead of eMail
.
But when I give
curl -X PUT localhost:8080/user/3 -H 'Content-type:application/json' -d '{"passwordHash":"12345","email":"admin1@admin.com"}'
it says :
Which is pretty horrific. I'm following this tutorial.
And here is my UserController
class:
package com.mua.cse616.Controller;
import com.mua.cse616.Model.User;
import com.mua.cse616.Model.UserNotFoundException;
import org.springframework.web.bind.annotation .*;
import java.util.List;
@RestController
class UserController {
private final UserRepository repository;
UserController(UserRepository repository) {
this.repository = repository;
}
// Aggregate root
@GetMapping("/user")
List<User> all() {
return repository.findAll();
}
@PostMapping("/user")
User newUser(@RequestBody User newUser) {
return repository.save(newUser);
}
// Single item
@GetMapping("/user/{id}")
User one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
@PutMapping("/user/{id}")
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
return repository.findById(id)
.map(employee -> {
employee.setEMail(newUser.getEMail());
employee.setPasswordHash(newUser.getPasswordHash());
return repository.save(employee);
})
.orElseGet(() -> {
newUser.setUserID(id);
return repository.save(newUser);
});
}
@DeleteMapping("/user/{id}")
void deleteUser(@PathVariable Long id) {
repository.deleteById(id);
}
}
Put method after updating :
@PutMapping(path="/user/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
User replaceUser(@RequestBody User newUser, @PathVariable Long id) {
return repository.findById(id)
.map(employee -> {
employee.setEMail(newUser.getEMail());
employee.setPasswordHash(newUser.getPasswordHash());
return repository.save(employee);
})
.orElseGet(() -> {
newUser.setUserID(id);
return repository.save(newUser);
});
}
Now there arise two questions.
- Why
email
instead ofeMail
, what to do to geteMail
instead ofemail
- How to
POST
correctly, what I'm doing wrong?