@GetMapping不会序列化ID

时间:2019-02-05 07:35:05

标签: java spring-boot java-8 spring-boot-jpa

我在 Spring boot 中遇到@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

这是下图:

The ids doesn't serialized in json

3 个答案:

答案 0 :(得分:3)

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

一种解决方案是使用Integer包装器类而不是int。 int的默认值为0,而Integer的为null。

答案 1 :(得分:2)

您必须在控制器中使用$ node app.js 7070 。您可以尝试以下方法:

  

实体:

function getProfiles(){
   return Profile.find()
       .then(profiles => {
          return profiles.map(profile =>{
             return {
                ...profile._doc
             };
          });
       }).catch(err => {
          //console.log(err);
          throw err;
       })
}

getProfiles().then(profiles => console.log('profiles',profiles))
  

控制器:

@PathVariable

答案 2 :(得分:0)

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

并且有模型的完整形式:

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