Spring Boot REST Hibernate - 创建用户

Man*_*anu 4 java rest hibernate jpa spring-boot

我尝试在我的后端创建一个函数来创建一个用户,我习惯于 Spring Boot、Hibernate、JPA、PostgreSQL……这是我的代码:

用户.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
    ...
}
Run Code Online (Sandbox Code Playgroud)

用户控制器.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);
}
Run Code Online (Sandbox Code Playgroud)

用户存储库.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByCountryId(Long countryId);

    List<User> findByCityId(Long cityId);
}
Run Code Online (Sandbox Code Playgroud)

我使用 Postman 进行测试。我尝试使用此 URL(1 = countryID,4 = cityId)和有效负载创建用户:

网址

localhost:8080/users/1/4
Run Code Online (Sandbox Code Playgroud)

有效载荷

{
    "name": "David",
    "username": "david",
    "password": "test",
}
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误...

错误:

{
    "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"
}
Run Code Online (Sandbox Code Playgroud)

2018-05-07 14:25:40.484 错误 17964 --- [io-8080-exec-10] oaccC[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] 在上下文中路径[]抛出异常[请求处理失败;嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; 嵌套异常是 java.lang.IllegalArgumentException: The given id must not be null!] 具有根本原因

但我不知道如何解决这个问题

Mạn*_*yễn 5

您应该将 PostgreSQL 中 id 列的数据类型设置为 SERIAL

更改@PathParam@PathVariable应该可以工作。

您使用了错误的注释。

编辑

Spring 使用注解做一些特殊的逻辑来从请求 URI 或请求正文中提取值并将它们映射到适当的带注释的参数。

您在参数上使用了错误的注释,因此未填充其值。

当你的仓库执行代码查找时null会抛出异常