1

@GetMappingSpring boot中遇到问题。

这是关于我的@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 does not serialize entity id

这是下图:

ids 没有在 json 中序列化

4

3 回答 3

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

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

于 2019-02-05T07:40:22.637 回答
2

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

实体:

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

控制器:

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserFromId(@PathVariable int id) {
    System.out.println(id); // should display the id
    // ...
}
于 2019-02-05T08:08:22.317 回答
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;
    }
}   
于 2019-02-09T06:18:40.573 回答