I try to create a function in my backend for create a user, I use to Spring Boot, Hibernate, JPA, PostgreSQL... This is my code:
User.java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@NotBlank
@Size(max = 100)
@Column(name = "firstName")
private String name;
@NotNull
@NotBlank
@Size(max = 30)
@Column(name = "username", unique = true)
private String username;
@NotNull
@NotBlank
@Size(max = 150)
@Column(name = "password")
private String password;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cityId", nullable = false)
@JsonIgnore
private City city;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countryId", nullable = false)
@JsonIgnore
private Country country;
// Getters and Setters
...
}
UserController.java
@PostMapping("/users/{countryId}/{cityId}")
public User createUser(@PathParam(value = "countryId") Long countryId, @PathParam(value = "cityId") Long cityId,
@Valid @RequestBody User user) {
user.setCountry(countryRepository.findById(countryId)
.orElseThrow(() -> new ResourceNotFoundException("Country not found with id " + countryId)));
user.setCity(cityRepository.findById(cityId)
.orElseThrow(() -> new ResourceNotFoundException("City not found with id " + cityId)));
return userRepository.save(user);
}
UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByCountryId(Long countryId);
List<User> findByCityId(Long cityId);
}
I use Postman for make a test. I try to create a user with this URL (1 = countryID, 4 = cityId) and Payload:
URL
localhost:8080/users/1/4
Payload
{
"name": "David",
"username": "david",
"password": "test",
}
and I received this error...
ERROR:
{
"timestamp": "2018-05-07T13:44:03.497+0000",
"status": 500,
"error": "Internal Server Error",
"message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
"path": "/users/1/4"
}
2018-05-07 14:25:40.484 ERROR 17964 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!] with root cause
But I don't know how resolve this problem
@Validas you have no id for your User you are creating.