【发布时间】:2018-10-17 08:35:24
【问题描述】:
我尝试在我的后端创建一个函数来创建一个用户,我使用 Spring Boot、Hibernate、JPA、PostgreSQL...这是我的代码:
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 创建一个用户:
网址
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.service() for 带有路径 [] 的上下文中的 servlet [dispatcherServlet] 引发异常 [请求处理失败;嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException:给定的 id 不能为空!;嵌套异常是 java.lang.IllegalArgumentException:给定的 id 不能为空!] 有根本原因
但我不知道如何解决这个问题
【问题讨论】:
-
服务器应该指出问题是由哪一行引起的。在不知道原因的情况下,它可能是
@Valid,因为您没有您正在创建的用户的 id。 -
这是给我的服务器信息:“2018-05-07 14:25:40.484 ERROR 17964 --- [io-8080-exec-10] occC[.[.[/]. [dispatcherServlet]:Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException:给定的 id 不能为空!;嵌套异常是java.lang.IllegalArgumentException: 给定的 id 不能为空!] 根本原因"
-
您的数据库管理员是什么?甲骨文或 MySQL
-
我的数据库管理员是 PostgreSQL
-
您是否分别有 id 1 和 4 的国家和城市的值,并且调试是否将两个值都设置为用户对象?由于您已将两个实体关系都标记为不为空,我只是想知道。
标签: java hibernate rest spring-boot jpa