我试图在后端创建一个用于创建用户的函数,我使用了Spring Boot、Hibernate、JPA和PostgreSQL...以下是我的代码:
User.java
我使用Postman进行测试。我尝试使用以下URL(其中1表示countryID,4表示cityId)和Payload创建一个用户:
有效载荷
我收到了这个错误...
错误:
2018-05-07 14:25:40.484错误17964 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]:在路径为[]的上下文中,对于servlet [dispatcherServlet]的Servlet.service()抛出异常[请求处理失败; 嵌套异常是org.springframework.dao.InvalidDataAccessApiUsageException:给定的id不能为空!; 嵌套异常是java.lang.IllegalArgumentException:给定的id不能为空!],但我不知道如何解决这个问题。
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);
}
我使用Postman进行测试。我尝试使用以下URL(其中1表示countryID,4表示cityId)和Payload创建一个用户:
URL
localhost:8080/users/1/4
有效载荷
{
"name": "David",
"username": "david",
"password": "test",
}
我收到了这个错误...
错误:
{
"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错误17964 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]:在路径为[]的上下文中,对于servlet [dispatcherServlet]的Servlet.service()抛出异常[请求处理失败; 嵌套异常是org.springframework.dao.InvalidDataAccessApiUsageException:给定的id不能为空!; 嵌套异常是java.lang.IllegalArgumentException:给定的id不能为空!],但我不知道如何解决这个问题。
@Valid
,因为您创建的用户没有 ID。 - Compass