@GetMapping 不序列化 ID

@GetMapping doesn't serialize Ids

我在 Spring 启动 中遇到 @GetMapping 的问题。

我的 @GetMapping 函数在从数据库中获取所有数据时没有在此模型上序列化我的 id

//User.java
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "username")
    private String username;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "joined_date")
    @CreatedDate
    private Date joinedDate;

    @Column(name = "password")
    private String password;

    @Column(name = "bio")
    private String bio;

    @Column(name = "email")
    private String email;
}

试了很多方法都解决不了。甚至这个问题:Spring boot @ResponseBody doesn't serialize entity id

这是下图:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

一个解决方案是使用 Integer wrapper class 而不是 int。 int 默认值为 0,Integer 为 null。

您必须在控制器中使用 @PathVariable。你可以试试这个:

Entity:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

Controller:

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserFromId(@PathVariable int id) {
    System.out.println(id); // should display the id
    // ...
}

我做到了!因为我忘记为模型添加 getter/setter 。还有更多的潜力我想告诉大家:

  • private int id 应该改为 private Integer id 正如 @Muhammad Vaqas 告诉我的
  • 试着看看这个问题的答案:Spring boot @ResponseBody doesn't serialize entity id

还有模型的完整形式:

package com.harrycoder.weebjournal.user;

import java.util.Date;

import javax.persistence.*;

import org.springframework.data.annotation.CreatedDate;

import com.fasterxml.jackson.annotation.*;

@Entity
@Table(name = "users")
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, 
        allowGetters = true)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "username")
    private String username;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "joined_date")
    @CreatedDate
    private Date joinedDate;

    @Column(name = "password")
    private String password;

    @Column(name = "bio")
    private String bio;

    @Column(name = "email")
    private String email;

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getBio() {
        return bio;
    }

    public String getEmail() {
        return email;
    }

    public Date getJoinedDate() {
        return joinedDate;
    }
}