I have 2 entity: User and UserDetails
Only one user detail can belong to one user.
/* class User */
@Entity
@Table(name = "users")
public class User {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "login")
private String login;
@Column(name = "password")
private String password;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL,
fetch = FetchType.LAZY, optional = false)
private UserDetails userDetails;
/* getters and setters */
}
/* class UserDetails */
@Entity
@Table(name = "userdetails")
public class UserDetails {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "surname")
private String surname;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
/* getters and setters */
}
This is class UserDetailsController:
@RestController
@RequestMapping("/userDetails")
public class UserDetailsController {
@GetMapping("/{id}")
public UserDetails findById(@PathVariable Long id) {
return userDetailsRepository.findById(id).orElseThrow(() -> new UserDetailsNotFoundException(id));
}
@GetMapping("/")
public Iterable<UserDetails> findAll() {
return userDetailsRepository.findAll();
}
@PostMapping("/")
public UserDetails save(@RequestBody UserDetails userDetails) {
return userDetailsRepository.save(userDetails);
}
@PostMapping(value = "/", params = {"name", "surname", "user_id"})
public UserDetails saveWithParams(@RequestParam("name") String name, @RequestParam("surname") String surname,
@RequestParam("user_id") Long userId) {
UserDetails userDetails = new UserDetails();
userDetails.setName(name);
userDetails.setSurname(surname);
User user = userRepository.findById(userId).orElseThrow(() -> new UserNotFoundException(userId));
userDetails.setUser(user);
return userDetailsRepository.save(userDetails);
}
}
This is how I'm trying to use my controller in .http file:
GET http://localhost:8080/userDetails/
###
GET http://localhost:8080/userDetails/4
###
POST http://localhost:8080/userDetails/
Content-Type: application/json
{
"name": "my name",
"surname": "my surname",
"user": {
"user_id": 12
}
}
###
POST http://localhost:8080/userDetails/
Content-Type: application/x-www-form-urlencoded
user_id=12&name=testName&surname=testSurname
###
1. Why first POST method not works: exception user_id can't be null?
2. Why both GET all method in userDetails returns something like this?:
