【问题标题】:Request not getting values of properties in Spring请求不获取 Spring 中的属性值
【发布时间】:2018-09-17 10:56:47
【问题描述】:

我有这门课:

@Entity
@Table(name = "users")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt"}, allowGetters = true)
public class User implements Serializable {
    @Id
    @NotBlank
    private String name;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;
}

这个仓库:

@Repository
public interface UserRepository extends JpaRepository<User, String> { }

还有这个控制器:

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    UserRepository userRepository;

    // Get All Users
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // Create a new User
    @PostMapping("/users")
    public User createUser(@Valid @RequestBody User user) {
        return userRepository.save(user);
    }
}

这是请求:

由于某种原因,它没有从正文中获取“名称”值,因此它返回了该错误。我需要字段“名称”是不是自动生成的 id(字符串)。

【问题讨论】:

  • 为您的实体添加 getter 和 setter。或者使用 JsonCreator 注释的构造函数及其使用 JsonProperty 注释的参数。
  • 请勿截图。

标签: java spring rest api spring-boot


【解决方案1】:

为您的用户实体生成 getter 和 setter:

    @Id
    @NotBlank
    private String name;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Date getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(Date createdAt) {
    this.createdAt = createdAt;
}

这应该可以解决您的 400 错误,我复制了您的代码,它对我有用

【讨论】:

    【解决方案2】:

    我似乎属性“名称”是某种受保护的属性,我将其更改为 “用户名”,现在可以使用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      相关资源
      最近更新 更多