gpt4 book ai didi

java - Spring Boot REST Hibernate - 创建用户

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:31 25 4
gpt4 key购买 nike

我尝试在我的后端创建一个函数来创建一个用户,我使用 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
...
}

用户 Controller .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)和有效负载创建用户:

网址

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 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

但是我不知道怎么解决这个问题

最佳答案

你应该在PostgreSQL中设置id列的数据类型为SERIAL

@PathParam 更改为 @PathVariable 应该有效。

您使用了错误的注释。

编辑

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

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

当您的存储库执行代码以针对null 查找时将抛出异常

关于java - Spring Boot REST Hibernate - 创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50215866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com